-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathUploaderModule.kt
More file actions
368 lines (347 loc) · 14.8 KB
/
UploaderModule.kt
File metadata and controls
368 lines (347 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package com.vydia.RNUploader
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import android.webkit.MimeTypeMap
import com.facebook.react.BuildConfig
import com.facebook.react.bridge.*
import net.gotev.uploadservice.UploadService
import net.gotev.uploadservice.UploadServiceConfig.httpStack
import net.gotev.uploadservice.UploadServiceConfig.initialize
import net.gotev.uploadservice.data.UploadNotificationConfig
import net.gotev.uploadservice.data.UploadNotificationStatusConfig
import net.gotev.uploadservice.observer.request.GlobalRequestObserver
import net.gotev.uploadservice.okhttp.OkHttpStack
import net.gotev.uploadservice.protocols.binary.BinaryUploadRequest
import net.gotev.uploadservice.protocols.multipart.MultipartUploadRequest
import okhttp3.OkHttpClient
import java.io.File
import java.util.concurrent.TimeUnit
class UploaderModule(val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), LifecycleEventListener {
private val TAG = "UploaderBridge"
private var notificationChannelID = "BackgroundUploadChannel"
private var isGlobalRequestObserver = false
override fun getName(): String {
return "RNFileUploader"
}
/*
Gets file information for the path specified. Example valid path is: /storage/extSdCard/DCIM/Camera/20161116_074726.mp4
Returns an object such as: {extension: "mp4", size: "3804316", exists: true, mimeType: "video/mp4", name: "20161116_074726.mp4"}
*/
@ReactMethod
fun getFileInfo(path: String?, promise: Promise) {
try {
val params = Arguments.createMap()
val fileInfo = File(path)
params.putString("name", fileInfo.name)
if (!fileInfo.exists() || !fileInfo.isFile) {
params.putBoolean("exists", false)
} else {
params.putBoolean("exists", true)
params.putString("size", fileInfo.length().toString()) //use string form of long because there is no putLong and converting to int results in a max size of 17.2 gb, which could happen. Javascript will need to convert it to a number
val extension = MimeTypeMap.getFileExtensionFromUrl(path)
params.putString("extension", extension)
val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())
params.putString("mimeType", mimeType)
}
promise.resolve(params)
} catch (exc: Exception) {
exc.printStackTrace()
Log.e(TAG, exc.message, exc)
promise.reject(exc)
}
}
private fun configureUploadServiceHTTPStack(options: ReadableMap, promise: Promise) {
var followRedirects = true
var followSslRedirects = true
var retryOnConnectionFailure = true
var connectTimeout = 15
var writeTimeout = 30
var readTimeout = 30
//TODO: make 'cache' customizable
if (options.hasKey("followRedirects")) {
if (options.getType("followRedirects") != ReadableType.Boolean) {
promise.reject(IllegalArgumentException("followRedirects must be a boolean."))
return
}
followRedirects = options.getBoolean("followRedirects")
}
if (options.hasKey("followSslRedirects")) {
if (options.getType("followSslRedirects") != ReadableType.Boolean) {
promise.reject(IllegalArgumentException("followSslRedirects must be a boolean."))
return
}
followSslRedirects = options.getBoolean("followSslRedirects")
}
if (options.hasKey("retryOnConnectionFailure")) {
if (options.getType("retryOnConnectionFailure") != ReadableType.Boolean) {
promise.reject(IllegalArgumentException("retryOnConnectionFailure must be a boolean."))
return
}
retryOnConnectionFailure = options.getBoolean("retryOnConnectionFailure")
}
if (options.hasKey("connectTimeout")) {
if (options.getType("connectTimeout") != ReadableType.Number) {
promise.reject(IllegalArgumentException("connectTimeout must be a number."))
return
}
connectTimeout = options.getInt("connectTimeout")
}
if (options.hasKey("writeTimeout")) {
if (options.getType("writeTimeout") != ReadableType.Number) {
promise.reject(IllegalArgumentException("writeTimeout must be a number."))
return
}
writeTimeout = options.getInt("writeTimeout")
}
if (options.hasKey("readTimeout")) {
if (options.getType("readTimeout") != ReadableType.Number) {
promise.reject(IllegalArgumentException("readTimeout must be a number."))
return
}
readTimeout = options.getInt("readTimeout")
}
httpStack = OkHttpStack(OkHttpClient().newBuilder()
.followRedirects(followRedirects)
.followSslRedirects(followSslRedirects)
.retryOnConnectionFailure(retryOnConnectionFailure)
.connectTimeout(connectTimeout.toLong(), TimeUnit.SECONDS)
.writeTimeout(writeTimeout.toLong(), TimeUnit.SECONDS)
.readTimeout(readTimeout.toLong(), TimeUnit.SECONDS)
.cache(null)
.build())
}
/*
* Starts a file upload.
* Returns a promise with the string ID of the upload.
*/
@ReactMethod
fun startUpload(options: ReadableMap, promise: Promise) {
val mandatoryParamsList: MutableList<String> = mutableListOf("url")
if (options.hasKey("files")) {
if (options.getType("files") != ReadableType.Array) {
promise.reject(java.lang.IllegalArgumentException("files must be an array."))
return
}
val files = options.getArray("files")
for (i in 0 until files!!.size()) {
val file = files.getMap(i)
if (!file.hasKey("path")) {
promise.reject(java.lang.IllegalArgumentException("Missing path field in files"))
return
}
}
} else {
mandatoryParamsList.add("path")
}
for (key in mandatoryParamsList) {
if (!options.hasKey(key)) {
promise.reject(java.lang.IllegalArgumentException("Missing '$key' field."))
return
}
if (options.getType(key) != ReadableType.String) {
promise.reject(java.lang.IllegalArgumentException("$key must be a string."))
return
}
}
if (options.hasKey("headers") && options.getType("headers") != ReadableType.Map) {
promise.reject(java.lang.IllegalArgumentException("headers must be a hash."))
return
}
if (options.hasKey("notification") && options.getType("notification") != ReadableType.Map) {
promise.reject(java.lang.IllegalArgumentException("notification must be a hash."))
return
}
configureUploadServiceHTTPStack(options, promise)
var requestType: String? = "raw"
val files = options.getArray("files")
if (files != null) {
requestType = "multipart";
} else if (options.hasKey("type")) {
requestType = options.getString("type")
if (requestType == null) {
promise.reject(java.lang.IllegalArgumentException("type must be string."))
return
}
if (requestType != "raw" && requestType != "multipart") {
promise.reject(java.lang.IllegalArgumentException("type should be string: raw or multipart."))
return
}
}
val notification: WritableMap = WritableNativeMap()
notification.putBoolean("enabled", true)
if (options.hasKey("notification")) {
notification.merge(options.getMap("notification")!!)
}
val application = reactContext.applicationContext as Application
reactContext.addLifecycleEventListener(this)
if (notification.hasKey("notificationChannel")) {
notificationChannelID = notification.getString("notificationChannel")!!
}
createNotificationChannel()
initialize(application, notificationChannelID, BuildConfig.DEBUG)
if(!isGlobalRequestObserver) {
isGlobalRequestObserver = true
GlobalRequestObserver(application, GlobalRequestObserverDelegate(reactContext))
}
val url = options.getString("url")
val filePath = options.getString("path")
val method = if (options.hasKey("method") && options.getType("method") == ReadableType.String) options.getString("method") else "POST"
val maxRetries = if (options.hasKey("maxRetries") && options.getType("maxRetries") == ReadableType.Number) options.getInt("maxRetries") else 2
val customUploadId = if (options.hasKey("customUploadId") && options.getType("method") == ReadableType.String) options.getString("customUploadId") else null
try {
val request = if (files != null) {
var request = MultipartUploadRequest(this.reactApplicationContext, url!!)
for (i in 0 until files.size()) {
val file = files.getMap(i)
request = request.addFileToUpload(file.getString("path")!!, file.getString("field") ?: "file${i}")
}
request
} else if (requestType == "raw") {
BinaryUploadRequest(this.reactApplicationContext, url!!)
.setFileToUpload(filePath!!)
} else {
if (!options.hasKey("field")) {
promise.reject(java.lang.IllegalArgumentException("field is required field for multipart type."))
return
}
if (options.getType("field") != ReadableType.String) {
promise.reject(java.lang.IllegalArgumentException("field must be string."))
return
}
MultipartUploadRequest(this.reactApplicationContext, url!!)
.addFileToUpload(filePath!!, options.getString("field")!!)
}
request.setMethod(method!!)
.setMaxRetries(maxRetries)
if (notification.getBoolean("enabled")) {
val notificationConfig = UploadNotificationConfig(
notificationChannelId = notificationChannelID,
isRingToneEnabled = notification.hasKey("enableRingTone") && notification.getBoolean("enableRingTone"),
progress = UploadNotificationStatusConfig(
title = if (notification.hasKey("onProgressTitle")) notification.getString("onProgressTitle")!! else "",
message = if (notification.hasKey("onProgressMessage")) notification.getString("onProgressMessage")!! else ""
),
success = UploadNotificationStatusConfig(
title = if (notification.hasKey("onCompleteTitle")) notification.getString("onCompleteTitle")!! else "",
message = if (notification.hasKey("onCompleteMessage")) notification.getString("onCompleteMessage")!! else "",
autoClear = notification.hasKey("autoClear") && notification.getBoolean("autoClear")
),
error = UploadNotificationStatusConfig(
title = if (notification.hasKey("onErrorTitle")) notification.getString("onErrorTitle")!! else "",
message = if (notification.hasKey("onErrorMessage")) notification.getString("onErrorMessage")!! else ""
),
cancelled = UploadNotificationStatusConfig(
title = if (notification.hasKey("onCancelledTitle")) notification.getString("onCancelledTitle")!! else "",
message = if (notification.hasKey("onCancelledMessage")) notification.getString("onCancelledMessage")!! else ""
)
)
request.setNotificationConfig { _, _ ->
notificationConfig
}
}
if (options.hasKey("parameters")) {
if (requestType == "raw") {
promise.reject(java.lang.IllegalArgumentException("Parameters supported only in multipart type"))
return
}
val parameters = options.getMap("parameters")
val keys = parameters!!.keySetIterator()
while (keys.hasNextKey()) {
val key = keys.nextKey()
if (parameters.getType(key) != ReadableType.String && parameters.getType(key) != ReadableType.Array) {
promise.reject(java.lang.IllegalArgumentException("Parameters must be string key/values or array key/List<String>. Value was invalid for '$key'"))
return
}
if(parameters.getType(key) == ReadableType.String){
request.addParameter(key, parameters.getString(key)!!)
}else{
val valuesParams = parameters.getArray(key)!!
val convertedValue = mutableListOf<String>()
for(i in 0 until valuesParams.size()){
val str = valuesParams.getString(i)
println("Log: $str")
convertedValue.add(str)
}
request.addArrayParameter(key, convertedValue)
}
}
}
if (options.hasKey("headers")) {
val headers = options.getMap("headers")
val keys = headers!!.keySetIterator()
while (keys.hasNextKey()) {
val key = keys.nextKey()
if (headers.getType(key) != ReadableType.String) {
promise.reject(java.lang.IllegalArgumentException("Headers must be string key/values. Value was invalid for '$key'"))
return
}
request.addHeader(key, headers.getString(key)!!)
}
}
if (customUploadId != null)
request.setUploadID(customUploadId)
val uploadId = request.startUpload()
promise.resolve(uploadId)
} catch (exc: java.lang.Exception) {
exc.printStackTrace()
Log.e(TAG, exc.message, exc)
promise.reject(exc)
}
}
/*
* Cancels file upload
* Accepts upload ID as a first argument, this upload will be cancelled
* Event "cancelled" will be fired when upload is cancelled.
*/
@ReactMethod
fun cancelUpload(cancelUploadId: String?, promise: Promise) {
if (cancelUploadId !is String) {
promise.reject(java.lang.IllegalArgumentException("Upload ID must be a string"))
return
}
try {
UploadService.stopUpload(cancelUploadId)
promise.resolve(true)
} catch (exc: java.lang.Exception) {
exc.printStackTrace()
Log.e(TAG, exc.message, exc)
promise.reject(exc)
}
}
/*
* Cancels all file uploads
*/
@ReactMethod
fun stopAllUploads(promise: Promise) {
try {
UploadService.stopAllUploads()
promise.resolve(true)
} catch (exc: java.lang.Exception) {
exc.printStackTrace()
Log.e(TAG, exc.message, exc)
promise.reject(exc)
}
}
// Customize the notification channel as you wish. This is only for a bare minimum example
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= 26) {
val channel = NotificationChannel(
notificationChannelID,
"Background Upload Channel",
NotificationManager.IMPORTANCE_LOW
)
val manager = reactApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
}
}
override fun onHostResume() {
}
override fun onHostPause() {
}
override fun onHostDestroy() {
}
}