Commit c9b2c666 authored by sunzheng's avatar sunzheng

init

parents
.imdone
testconfig
RNFetchBlobTest/
test/test-server/public/*
!test/test-server/public/github.png
# OSX
#
.DS_Store
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace
# Android/IJ
#
.idea
.gradle
local.properties
# node.js
#
node_modules/
npm-debug.log
# BUCK
buck-out/
\.buckd/
android/app/libs
android/keystores/debug.keystore
For developers who interested in making contribution to this project, please see [https://github.com/joltup/rn-fetch-blob-dev](https://github.com/joltup/rn-fetch-blob-dev) for more information.
960px <pinovel@gmail.com>
Amerrnath <amerrnath.21@gmail.com>
Andreas Amsenius <andreas@amsenius.se>
Andrew Jack <me@andrewjack.uk>
Arthur Ouaki <arthur.ouaki@gmail.com>
Ben <benhsieh@catchplay.com>
Ben Hsieh <benhsieh@catchplay.com>
Binur Konarbai <binur95@gmail.com>
Bronco <heybronco@gmail.com>
Chris Sloey <chris@addjam.com>
Corentin Smith <corentin.smith@gmail.com>
Dmitry Petukhov <dmitryvpetukhov@gmail.com>
Dombi Soma Kristóf <dombis@sonrisa.hu>
Erik Smartt <code@eriksmartt.com>
Evgeniy Baraniuk <ev.baraniuk@gmail.com>
Frank van der Hoek <frank.vanderhoek@gmail.com>
Guy Blank <blank.guy@gmail.com>
Jacob Lauritzen <jacsebl@hotmail.com>
Jeremi Stadler <stadler.jeremi@gmail.com>
Jon San Miguel <sanmiguelje@gmail.com>
Juan B. Rodriguez <jbrodriguez@gmail.com>
Kaishley <kklingachetti@msn.com>
Martin Giachetti <martin.giachetti@gmail.com>
Max Gurela <maxpowa1@gmail.com>
Mike Monteith <mike@mikemonteith.com>
Naoki AINOYA <ainonic@gmail.com>
Nguyen Cao Nhat Linh <nhatlinh95@gmail.com>
Nick Pomfret <npomfret@users.noreply.github.com>
Oliver <spendabuk@hotmail.com>
Petter Hesselberg <petterh@microsoft.com>
Reza Ghorbani <r.ghorbani.f@gmail.com>
Simón Gómez <simongomez95@gmail.com>
Steve Liles <steveliles@gmail.com>
Tim Suchanek <tim.suchanek@gmail.com>
Yonsh Lin <yonsh@live.com>
atlanteh <atlanteh@gmail.com>
follower <github@rancidbacon.com>
francisco-sanchez-molina <psm1984@gmail.com>
gferreyra91 <gferreyra91@gmail.com>
hhravn <hhravn@gmail.com>
kejinliang <kejinliang@users.noreply.github.com>
pedramsaleh <spmact@yahoo.ca>
smartt <github@eriksmartt.com>
MIT License
Copyright (c) 2017 xeiyan@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
// Copyright 2016 wkh237@github. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
import {
NativeModules,
DeviceEventEmitter,
Platform,
NativeAppEventEmitter,
} from 'react-native'
const RNFetchBlob:RNFetchBlobNative = NativeModules.RNFetchBlob
/**
* Send an intent to open the file.
* @param {string} path Path of the file to be open.
* @param {string} mime MIME type string
* @return {Promise}
*/
function actionViewIntent(path:string, mime:string = 'text/plain') {
if(Platform.OS === 'android')
return RNFetchBlob.actionViewIntent(path, mime)
else
return Promise.reject('RNFetchBlob.android.actionViewIntent only supports Android.')
}
function getContentIntent(mime:string) {
if(Platform.OS === 'android')
return RNFetchBlob.getContentIntent(mime)
else
return Promise.reject('RNFetchBlob.android.getContentIntent only supports Android.')
}
function addCompleteDownload(config) {
if(Platform.OS === 'android')
return RNFetchBlob.addCompleteDownload(config)
else
return Promise.reject('RNFetchBlob.android.addCompleteDownload only supports Android.')
}
function getSDCardDir() {
if(Platform.OS === 'android')
return RNFetchBlob.getSDCardDir()
else
return Promise.reject('RNFetchBlob.android.getSDCardDir only supports Android.')
}
function getSDCardApplicationDir() {
if(Platform.OS === 'android')
return RNFetchBlob.getSDCardApplicationDir()
else
return Promise.reject('RNFetchBlob.android.getSDCardApplicationDir only supports Android.')
}
export default {
actionViewIntent,
getContentIntent,
addCompleteDownload,
getSDCardDir,
getSDCardApplicationDir,
}
# Built application files
*.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# Intellij
*.iml
# Keystore files
*.jks
# Eclipse Metadata
.metadata/
#
# Mac OS X clutter
*.DS_Store
#
# Windows clutter
Thumbs.db
#
# # Intellij IDEA (see https://intellij-support.jetbrains.com/entries/23393067)
*.iws
.idea/libraries
.idea/tasks.xml
.idea/vcs.xml
.idea/workspace.xml
apply plugin: 'com.android.library'
def safeExtGet(prop, fallback) {
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}
repositories {
mavenCentral()
jcenter()
google()
}
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
}
}
android {
compileSdkVersion safeExtGet('compileSdkVersion', 28)
buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3')
defaultConfig {
minSdkVersion safeExtGet('minSdkVersion', 16)
targetSdkVersion safeExtGet('targetSdkVersion', 28)
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation "com.facebook.react:react-native:${safeExtGet('reactNativeVersion', '+')}"
//compile 'com.squareup.okhttp3:okhttp:+'
//{RNFetchBlob_PRE_0.28_DEPDENDENCY}
}
android.enableJetifier=true
android.useAndroidX=true
\ No newline at end of file
#Fri Jun 01 10:33:07 BRT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/xeiyan/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.RNFetchBlob">
<!-- Required to access Google Play Licensing -->
<uses-permission android:name="com.android.vending.CHECK_LICENSE" />
<!-- Required to download files from Google Play -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Required to keep CPU alive while downloading files
(NOT to keep screen awake) -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Required to poll the state of the network connection
and respond to changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Required to check whether Wi-Fi is enabled -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- Required to read and write the expansion files on shared storage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="@string/app_name">
<provider
android:name="com.RNFetchBlob.Utils.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
</application>
</manifest>
This diff is collapsed.
This diff is collapsed.
package com.RNFetchBlob;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
class RNFetchBlobConfig {
public Boolean fileCache;
public String path;
public String appendExt;
public ReadableMap addAndroidDownloads;
public Boolean trusty;
public Boolean wifiOnly = false;
public String key;
public String mime;
public Boolean auto;
public Boolean overwrite = true;
public long timeout = 60000;
public Boolean increment = false;
public Boolean followRedirect = true;
public ReadableArray binaryContentTypes = null;
RNFetchBlobConfig(ReadableMap options) {
if(options == null)
return;
this.fileCache = options.hasKey("fileCache") ? options.getBoolean("fileCache") : false;
this.path = options.hasKey("path") ? options.getString("path") : null;
this.appendExt = options.hasKey("appendExt") ? options.getString("appendExt") : "";
this.trusty = options.hasKey("trusty") ? options.getBoolean("trusty") : false;
this.wifiOnly = options.hasKey("wifiOnly") ? options.getBoolean("wifiOnly") : false;
if(options.hasKey("addAndroidDownloads")) {
this.addAndroidDownloads = options.getMap("addAndroidDownloads");
}
if(options.hasKey("binaryContentTypes"))
this.binaryContentTypes = options.getArray("binaryContentTypes");
if(this.path != null && path.toLowerCase().contains("?append=true")) {
this.overwrite = false;
}
if(options.hasKey("overwrite"))
this.overwrite = options.getBoolean("overwrite");
if(options.hasKey("followRedirect")) {
this.followRedirect = options.getBoolean("followRedirect");
}
this.key = options.hasKey("key") ? options.getString("key") : null;
this.mime = options.hasKey("contentType") ? options.getString("contentType") : null;
this.increment = options.hasKey("increment") ? options.getBoolean("increment") : false;
this.auto = options.hasKey("auto") ? options.getBoolean("auto") : false;
if(options.hasKey("timeout")) {
this.timeout = options.getInt("timeout");
}
}
}
package com.RNFetchBlob;
public class RNFetchBlobConst {
public static final String EVENT_UPLOAD_PROGRESS = "RNFetchBlobProgress-upload";
public static final String EVENT_PROGRESS = "RNFetchBlobProgress";
public static final String EVENT_HTTP_STATE = "RNFetchBlobState";
public static final String EVENT_MESSAGE = "RNFetchBlobMessage";
public static final String FILE_PREFIX = "RNFetchBlob-file://";
public static final String CONTENT_PREFIX = "RNFetchBlob-content://";
public static final String FILE_PREFIX_BUNDLE_ASSET = "bundle-assets://";
public static final String FILE_PREFIX_CONTENT = "content://";
public static final String DATA_ENCODE_URI = "uri";
public static final String RNFB_RESPONSE_BASE64 = "base64";
public static final String RNFB_RESPONSE_UTF8 = "utf8";
public static final String RNFB_RESPONSE_PATH = "path";
public static final Integer GET_CONTENT_INTENT = 99900;
}
This diff is collapsed.
package com.RNFetchBlob;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RNFetchBlobPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new RNFetchBlob(reactContext));
return modules;
}
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
package com.RNFetchBlob;
/**
* Created by wkh237 on 2016/9/24.
*/
public class RNFetchBlobProgressConfig {
enum ReportType {
Upload,
Download
};
private long lastTick = 0;
private int tick = 0;
private int count = -1;
private int interval = -1;
private boolean enable = false;
private ReportType type = ReportType.Download;
RNFetchBlobProgressConfig(boolean report, int interval, int count, ReportType type) {
this.enable = report;
this.interval = interval;
this.type = type;
this.count = count;
}
public boolean shouldReport(float progress) {
boolean checkCount = true;
if(count > 0 && progress > 0)
checkCount = Math.floor(progress*count)> tick;
boolean result = (System.currentTimeMillis() - lastTick> interval) && enable && checkCount;
if(result) {
tick++;
lastTick = System.currentTimeMillis();
}
return result;
}
}
This diff is collapsed.
package com.RNFetchBlob;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
public class RNFetchBlobUtils {
public static String getMD5(String input) {
String result = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
result = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// TODO: Is discarding errors the intent? (https://www.owasp.org/index.php/Return_Inside_Finally_Block)
return result;
}
}
public static void emitWarningEvent(String data) {
WritableMap args = Arguments.createMap();
args.putString("event", "warn");
args.putString("detail", data);
// emit event to js context
RNFetchBlob.RCTContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RNFetchBlobConst.EVENT_MESSAGE, args);
}
public static OkHttpClient.Builder getUnsafeOkHttpClient(OkHttpClient client) {
try {
// Create a trust manager that does not validate certificate chains
final X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
};
final TrustManager[] trustAllCerts = new TrustManager[]{ x509TrustManager };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = client.newBuilder();
builder.sslSocketFactory(sslSocketFactory, x509TrustManager);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.RNFetchBlob.Response;
import com.RNFetchBlob.RNFetchBlobConst;
import com.RNFetchBlob.RNFetchBlobProgressConfig;
import com.RNFetchBlob.RNFetchBlobReq;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.IOException;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;
import okio.Timeout;
/**
* Created by wkh237 on 2016/7/11.
*/
public class RNFetchBlobDefaultResp extends ResponseBody {
String mTaskId;
ReactApplicationContext rctContext;
ResponseBody originalBody;
boolean isIncrement = false;
public RNFetchBlobDefaultResp(ReactApplicationContext ctx, String taskId, ResponseBody body, boolean isIncrement) {
this.rctContext = ctx;
this.mTaskId = taskId;
this.originalBody = body;
this.isIncrement = isIncrement;
}
@Override
public MediaType contentType() {
return originalBody.contentType();
}
@Override
public long contentLength() {
return originalBody.contentLength();
}
@Override
public BufferedSource source() {
return Okio.buffer(new ProgressReportingSource(originalBody.source()));
}
private class ProgressReportingSource implements Source {
BufferedSource mOriginalSource;
long bytesRead = 0;
ProgressReportingSource(BufferedSource originalSource) {
mOriginalSource = originalSource;
}
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long read = mOriginalSource.read(sink, byteCount);
bytesRead += read > 0 ? read : 0;
RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
long cLen = contentLength();
if(reportConfig != null && cLen != 0 && reportConfig.shouldReport(bytesRead/contentLength())) {
WritableMap args = Arguments.createMap();
args.putString("taskId", mTaskId);
args.putString("written", String.valueOf(bytesRead));
args.putString("total", String.valueOf(contentLength()));
if(isIncrement) {
args.putString("chunk", sink.readString(Charset.defaultCharset()));
}
else {
args.putString("chunk", "");
}
rctContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RNFetchBlobConst.EVENT_PROGRESS, args);
}
return read;
}
@Override
public Timeout timeout() {
return null;
}
@Override
public void close() throws IOException {
}
}
}
package com.RNFetchBlob.Response;
import androidx.annotation.NonNull;
import com.RNFetchBlob.RNFetchBlobConst;
import com.RNFetchBlob.RNFetchBlobProgressConfig;
import com.RNFetchBlob.RNFetchBlobReq;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;
import okio.Timeout;
/**
* Created by wkh237 on 2016/7/11.
*/
public class RNFetchBlobFileResp extends ResponseBody {
String mTaskId;
ResponseBody originalBody;
String mPath;
long bytesDownloaded = 0;
ReactApplicationContext rctContext;
FileOutputStream ofStream;
boolean isEndMarkerReceived;
public RNFetchBlobFileResp(ReactApplicationContext ctx, String taskId, ResponseBody body, String path, boolean overwrite) throws IOException {
super();
this.rctContext = ctx;
this.mTaskId = taskId;
this.originalBody = body;
assert path != null;
this.mPath = path;
this.isEndMarkerReceived = false;
if (path != null) {
boolean appendToExistingFile = !overwrite;
path = path.replace("?append=true", "");
mPath = path;
File f = new File(path);
File parent = f.getParentFile();
if(parent != null && !parent.exists() && !parent.mkdirs()){
throw new IllegalStateException("Couldn't create dir: " + parent);
}
if(!f.exists())
f.createNewFile();
ofStream = new FileOutputStream(new File(path), appendToExistingFile);
}
}
@Override
public MediaType contentType() {
return originalBody.contentType();
}
@Override
public long contentLength() {
return originalBody.contentLength();
}
public boolean isDownloadComplete() {
return (bytesDownloaded == contentLength()) // Case of non-chunked downloads
|| (contentLength() == -1 && isEndMarkerReceived); // Case of chunked downloads
}
@Override
public BufferedSource source() {
ProgressReportingSource countable = new ProgressReportingSource();
return Okio.buffer(countable);
}
private class ProgressReportingSource implements Source {
@Override
public long read(@NonNull Buffer sink, long byteCount) throws IOException {
try {
byte[] bytes = new byte[(int) byteCount];
long read = originalBody.byteStream().read(bytes, 0, (int) byteCount);
bytesDownloaded += read > 0 ? read : 0;
if (read > 0) {
ofStream.write(bytes, 0, (int) read);
} else if (contentLength() == -1 && read == -1) {
// End marker has been received for chunked download
isEndMarkerReceived = true;
}
RNFetchBlobProgressConfig reportConfig = RNFetchBlobReq.getReportProgress(mTaskId);
if (contentLength() != 0) {
// For non-chunked download, progress is received / total
// For chunked download, progress can be either 0 (started) or 1 (ended)
float progress = (contentLength() != -1) ? bytesDownloaded / contentLength() : ( ( isEndMarkerReceived ) ? 1 : 0 );
if (reportConfig != null && reportConfig.shouldReport(progress /* progress */)) {
if (contentLength() != -1) {
// For non-chunked downloads
reportProgress(mTaskId, bytesDownloaded, contentLength());
} else {
// For chunked downloads
if (!isEndMarkerReceived) {
reportProgress(mTaskId, 0, contentLength());
} else{
reportProgress(mTaskId, bytesDownloaded, bytesDownloaded);
}
}
}
}
return read;
} catch(Exception ex) {
return -1;
}
}
private void reportProgress(String taskId, long bytesDownloaded, long contentLength) {
WritableMap args = Arguments.createMap();
args.putString("taskId", taskId);
args.putString("written", String.valueOf(bytesDownloaded));
args.putString("total", String.valueOf(contentLength));
rctContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(RNFetchBlobConst.EVENT_PROGRESS, args);
}
@Override
public Timeout timeout() {
return null;
}
@Override
public void close() throws IOException {
ofStream.close();
}
}
}
package com.RNFetchBlob.Utils;
public class FileProvider extends androidx.core.content.FileProvider {
}
package com.RNFetchBlob.Utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.content.ContentUris;
import android.os.Environment;
import android.content.ContentResolver;
import com.RNFetchBlob.RNFetchBlobUtils;
import java.io.File;
import java.io.InputStream;
import java.io.FileOutputStream;
public class PathResolver {
@TargetApi(19)
public static String getRealPathFromURI(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
try {
final String id = DocumentsContract.getDocumentId(uri);
//Starting with Android O, this "id" is not necessarily a long (row number),
//but might also be a "raw:/some/file/path" URL
if (id != null && id.startsWith("raw:/")) {
Uri rawuri = Uri.parse(id);
String path = rawuri.getPath();
return path;
}
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
catch (Exception ex) {
//something went wrong, but android should still be able to handle the original uri by returning null here (see readFile(...))
return null;
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// Other Providers
else{
try {
InputStream attachment = context.getContentResolver().openInputStream(uri);
if (attachment != null) {
String filename = getContentName(context.getContentResolver(), uri);
if (filename != null) {
File file = new File(context.getCacheDir(), filename);
FileOutputStream tmp = new FileOutputStream(file);
byte[] buffer = new byte[1024];
while (attachment.read(buffer) > 0) {
tmp.write(buffer);
}
tmp.close();
attachment.close();
return file.getAbsolutePath();
}
}
} catch (Exception e) {
RNFetchBlobUtils.emitWarningEvent(e.toString());
return null;
}
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
private static String getContentName(ContentResolver resolver, Uri uri) {
Cursor cursor = resolver.query(uri, null, null, null, null);
cursor.moveToFirst();
int nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
if (nameIndex >= 0) {
String name = cursor.getString(nameIndex);
cursor.close();
return name;
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
String result = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
result = cursor.getString(index);
}
}
catch (Exception ex) {
ex.printStackTrace();
return null;
}
finally {
if (cursor != null)
cursor.close();
}
return result;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment