-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
See #13
- Loading branch information
Showing
11 changed files
with
408 additions
and
159 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
125 changes: 125 additions & 0 deletions
125
android/src/main/java/com/alpha0010/fs/NetworkHandler.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
package com.alpha0010.fs | ||
|
||
import com.facebook.react.bridge.Arguments | ||
import com.facebook.react.bridge.ReactContext | ||
import com.facebook.react.bridge.ReadableMap | ||
import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter | ||
import com.facebook.react.modules.network.OkHttpClientProvider | ||
import okhttp3.* | ||
import java.io.IOException | ||
|
||
const val FETCH_EVENT = "FetchEvent" | ||
|
||
class NetworkHandler(reactContext: ReactContext) { | ||
private val emitter = reactContext.getJSModule(RCTDeviceEventEmitter::class.java) | ||
|
||
fun fetch(requestId: Int, resource: String, init: ReadableMap) { | ||
val request = try { | ||
buildRequest(resource, init) | ||
} catch (e: Throwable) { | ||
onFetchError(requestId, e) | ||
return | ||
} | ||
|
||
// Share client with RN core library. | ||
val call = getClient { bytesRead, contentLength, done -> | ||
emitter.emit( | ||
FETCH_EVENT, Arguments.makeNativeMap( | ||
mapOf( | ||
"requestId" to requestId, | ||
"state" to "progress", | ||
"bytesRead" to bytesRead, | ||
"contentLength" to contentLength, | ||
"done" to done | ||
) | ||
) | ||
) | ||
}.newCall(request) | ||
call.enqueue(object : Callback { | ||
override fun onFailure(call: Call, e: IOException) { | ||
onFetchError(requestId, e) | ||
} | ||
|
||
override fun onResponse(call: Call, response: Response) { | ||
try { | ||
response.use { | ||
if (init.hasKey("path")) { | ||
parsePathToFile(init.getString("path")!!) | ||
.outputStream() | ||
.use { response.body()!!.byteStream().copyTo(it) } | ||
} | ||
|
||
val headers = response.headers().names().map { it to response.header(it) } | ||
emitter.emit( | ||
FETCH_EVENT, Arguments.makeNativeMap( | ||
mapOf( | ||
"requestId" to requestId, | ||
"state" to "complete", | ||
"headers" to Arguments.makeNativeMap(headers.toMap()), | ||
"ok" to response.isSuccessful, | ||
"redirected" to response.isRedirect, | ||
"status" to response.code(), | ||
"statusText" to response.message(), | ||
"url" to response.request().url().toString() | ||
) | ||
) | ||
) | ||
} | ||
} catch (e: Throwable) { | ||
onFetchError(requestId, e) | ||
} | ||
} | ||
}) | ||
} | ||
|
||
private fun buildRequest(resource: String, init: ReadableMap): Request { | ||
// Request will be saved to a file, no reason to also save in cache. | ||
val builder = Request.Builder() | ||
.url(resource) | ||
.cacheControl(CacheControl.Builder().noStore().build()) | ||
|
||
if (init.hasKey("method")) { | ||
if (init.hasKey("body")) { | ||
builder.method( | ||
init.getString("method")!!, | ||
RequestBody.create(null, init.getString("body")!!) | ||
) | ||
} else { | ||
builder.method(init.getString("method")!!, null) | ||
} | ||
} | ||
|
||
if (init.hasKey("headers")) { | ||
for (header in init.getMap("headers")!!.entryIterator) { | ||
builder.header(header.key, header.value as String) | ||
} | ||
} | ||
|
||
return builder.build() | ||
} | ||
|
||
private fun getClient(listener: ProgressListener): OkHttpClient { | ||
return OkHttpClientProvider | ||
.getOkHttpClient() | ||
.newBuilder() | ||
.addNetworkInterceptor { chain -> | ||
val originalResponse = chain.proceed(chain.request()) | ||
originalResponse.body() | ||
?.let { originalResponse.newBuilder().body(ProgressResponseBody(it, listener)).build() } | ||
?: originalResponse | ||
} | ||
.build() | ||
} | ||
|
||
private fun onFetchError(requestId: Int, e: Throwable) { | ||
emitter.emit( | ||
FETCH_EVENT, Arguments.makeNativeMap( | ||
mapOf( | ||
"requestId" to requestId, | ||
"state" to "error", | ||
"message" to e.localizedMessage | ||
) | ||
) | ||
) | ||
} | ||
} |
43 changes: 43 additions & 0 deletions
43
android/src/main/java/com/alpha0010/fs/ProgressResponseBody.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package com.alpha0010.fs | ||
|
||
import okhttp3.ResponseBody | ||
import okio.Buffer | ||
import okio.BufferedSource | ||
import okio.ForwardingSource | ||
import okio.Okio | ||
|
||
typealias ProgressListener = (bytesRead: Long, contentLength: Long, done: Boolean) -> Unit | ||
|
||
const val MIN_EVENT_INTERVAL = 150L | ||
|
||
class ProgressResponseBody( | ||
private val responseBody: ResponseBody, | ||
private val listener: ProgressListener | ||
) : ResponseBody() { | ||
private var bufferedSource: BufferedSource? = null | ||
private var lastEventTime = 0L | ||
|
||
override fun contentType() = responseBody.contentType() | ||
|
||
override fun contentLength() = responseBody.contentLength() | ||
|
||
override fun source(): BufferedSource { | ||
return bufferedSource ?: Okio.buffer(object : ForwardingSource(responseBody.source()) { | ||
var totalBytesRead = 0L | ||
|
||
override fun read(sink: Buffer, byteCount: Long): Long { | ||
val bytesRead = super.read(sink, byteCount) | ||
val isDone = bytesRead == -1L | ||
totalBytesRead += if (isDone) 0 else bytesRead | ||
|
||
val currentTime = System.currentTimeMillis() | ||
if (currentTime - lastEventTime > MIN_EVENT_INTERVAL || isDone) { | ||
lastEventTime = currentTime | ||
listener(totalBytesRead, contentLength(), isDone) | ||
} | ||
|
||
return bytesRead | ||
} | ||
}).also { bufferedSource = it } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package com.alpha0010.fs | ||
|
||
import android.net.Uri | ||
import java.io.File | ||
|
||
/** | ||
* Return a File object and do some basic sanitization of the passed path. | ||
*/ | ||
fun parsePathToFile(path: String): File { | ||
return if (path.contains("://")) { | ||
try { | ||
val pathUri = Uri.parse(path) | ||
File(pathUri.path!!) | ||
} catch (e: Throwable) { | ||
File(path) | ||
} | ||
} else { | ||
File(path) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
#import <React/RCTBridgeModule.h> | ||
#import <React/RCTEventEmitter.h> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.