mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-17 22:26:09 +08:00
Compare commits
15 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
ebb5defb10 | ||
![]() |
a509ff8e30 | ||
![]() |
59fcba15ee | ||
![]() |
c6f9bb20a1 | ||
![]() |
9e6c7ea769 | ||
![]() |
f461c8ddd2 | ||
![]() |
4cbeb7bec4 | ||
![]() |
ed7f5ac606 | ||
![]() |
6abb2c7a5d | ||
![]() |
a4a372f17e | ||
![]() |
48693e3b45 | ||
![]() |
2d805fb38e | ||
![]() |
92c421b30f | ||
![]() |
dbd0880295 | ||
![]() |
f110df1206 |
7
.gitignore
vendored
7
.gitignore
vendored
@@ -1,7 +1,6 @@
|
|||||||
/.idea
|
.vscode
|
||||||
/node_modules
|
android/build
|
||||||
/android/build
|
android/obj
|
||||||
/android/obj
|
|
||||||
*.iml
|
*.iml
|
||||||
|
|
||||||
# OSX
|
# OSX
|
||||||
|
19
.npmignore
19
.npmignore
@@ -1,11 +1,11 @@
|
|||||||
/.idea
|
.babelrc
|
||||||
/.babelrc
|
.npmignore
|
||||||
/.npmignore
|
.eslintrc
|
||||||
/.eslintrc
|
.nvmrc
|
||||||
/.nvmrc
|
.travis.yml
|
||||||
/.travis.yml
|
Example
|
||||||
/Example
|
android/build
|
||||||
/android/build
|
.vscode
|
||||||
|
|
||||||
# OSX
|
# OSX
|
||||||
#
|
#
|
||||||
@@ -45,4 +45,5 @@ Example
|
|||||||
yarn.lock
|
yarn.lock
|
||||||
android/jni
|
android/jni
|
||||||
|
|
||||||
domains.json
|
domains.json
|
||||||
|
endpoints.json
|
@@ -8,6 +8,7 @@ import {
|
|||||||
TouchableOpacity,
|
TouchableOpacity,
|
||||||
Linking,
|
Linking,
|
||||||
Image,
|
Image,
|
||||||
|
NativeModules,
|
||||||
} from 'react-native';
|
} from 'react-native';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -51,22 +52,26 @@ export default class App extends Component {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
doUpdate = async info => {
|
doUpdate = async info => {
|
||||||
const hash = await downloadUpdate(info);
|
try {
|
||||||
Alert.alert('提示', '下载完毕,是否重启应用?', [
|
const hash = await downloadUpdate(info);
|
||||||
{
|
Alert.alert('提示', '下载完毕,是否重启应用?', [
|
||||||
text: '是',
|
{
|
||||||
onPress: () => {
|
text: '是',
|
||||||
switchVersion(hash);
|
onPress: () => {
|
||||||
|
switchVersion(hash);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{text: '否'},
|
||||||
{text: '否'},
|
{
|
||||||
{
|
text: '下次启动时',
|
||||||
text: '下次启动时',
|
onPress: () => {
|
||||||
onPress: () => {
|
switchVersionLater(hash);
|
||||||
switchVersionLater(hash);
|
},
|
||||||
},
|
},
|
||||||
},
|
]);
|
||||||
]);
|
} catch (err) {
|
||||||
|
Alert.alert('更新失败', err.message);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
checkUpdate = async () => {
|
checkUpdate = async () => {
|
||||||
@@ -74,7 +79,7 @@ export default class App extends Component {
|
|||||||
try {
|
try {
|
||||||
info = await checkUpdate(appKey);
|
info = await checkUpdate(appKey);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn(err);
|
Alert.alert('更新检查失败', err.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (info.expired) {
|
if (info.expired) {
|
||||||
@@ -111,14 +116,14 @@ export default class App extends Component {
|
|||||||
<Text style={styles.welcome}>欢迎使用热更新服务</Text>
|
<Text style={styles.welcome}>欢迎使用热更新服务</Text>
|
||||||
<Image
|
<Image
|
||||||
resizeMode={'contain'}
|
resizeMode={'contain'}
|
||||||
source={require('./assets/shoucang.png')}
|
source={require('./assets/shezhi.png')}
|
||||||
style={styles.image}
|
style={styles.image}
|
||||||
/>
|
/>
|
||||||
<Text style={styles.instructions}>
|
<Text style={styles.instructions}>
|
||||||
这是版本一 {'\n'}
|
这是版本一 {'\n'}
|
||||||
当前包版本号: {packageVersion}
|
当前原生包版本号: {packageVersion}
|
||||||
{'\n'}
|
{'\n'}
|
||||||
当前版本Hash: {currentVersion || '(空)'}
|
当前热更新版本Hash: {currentVersion || '(空)'}
|
||||||
{'\n'}
|
{'\n'}
|
||||||
</Text>
|
</Text>
|
||||||
<TouchableOpacity onPress={this.checkUpdate}>
|
<TouchableOpacity onPress={this.checkUpdate}>
|
||||||
|
@@ -41,6 +41,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
final int DOWNLOAD_CHUNK_SIZE = 4096;
|
final int DOWNLOAD_CHUNK_SIZE = 4096;
|
||||||
|
|
||||||
Context context;
|
Context context;
|
||||||
|
String hash;
|
||||||
|
|
||||||
DownloadTask(Context context) {
|
DownloadTask(Context context) {
|
||||||
this.context = context;
|
this.context = context;
|
||||||
@@ -69,7 +70,10 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void downloadFile(String url, File writePath) throws IOException {
|
private void downloadFile(DownloadTaskParams param) throws IOException {
|
||||||
|
String url = param.url;
|
||||||
|
File writePath = param.zipFilePath;
|
||||||
|
this.hash = param.hash;
|
||||||
OkHttpClient client = new OkHttpClient();
|
OkHttpClient client = new OkHttpClient();
|
||||||
Request request = new Request.Builder().url(url)
|
Request request = new Request.Builder().url(url)
|
||||||
.build();
|
.build();
|
||||||
@@ -92,21 +96,17 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
long bytesRead = 0;
|
long bytesRead = 0;
|
||||||
long totalRead = 0;
|
long received = 0;
|
||||||
double lastProgressValue=0;
|
|
||||||
while ((bytesRead = source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE)) != -1) {
|
while ((bytesRead = source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE)) != -1) {
|
||||||
totalRead += bytesRead;
|
received += bytesRead;
|
||||||
sink.emit();
|
sink.emit();
|
||||||
if (UpdateContext.DEBUG) {
|
if (UpdateContext.DEBUG) {
|
||||||
Log.d("RNUpdate", "Progress " + totalRead + "/" + contentLength);
|
Log.d("RNUpdate", "Progress " + received + "/" + contentLength);
|
||||||
}
|
|
||||||
double progress = Math.round(((double) totalRead * 100) / contentLength);
|
|
||||||
if ((progress != lastProgressValue) || (totalRead == contentLength)) {
|
|
||||||
lastProgressValue = progress;
|
|
||||||
publishProgress(new long[]{(long)progress,totalRead, contentLength});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
publishProgress(new long[]{received, contentLength});
|
||||||
}
|
}
|
||||||
if (totalRead != contentLength) {
|
if (received != contentLength) {
|
||||||
throw new Error("Unexpected eof while reading ppk");
|
throw new Error("Unexpected eof while reading ppk");
|
||||||
}
|
}
|
||||||
sink.writeAll(source);
|
sink.writeAll(source);
|
||||||
@@ -121,10 +121,10 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
protected void onProgressUpdate(long[]... values) {
|
protected void onProgressUpdate(long[]... values) {
|
||||||
super.onProgressUpdate(values);
|
super.onProgressUpdate(values);
|
||||||
WritableMap params = Arguments.createMap();
|
WritableMap params = Arguments.createMap();
|
||||||
params.putDouble("progress", (values[0][0]));
|
params.putDouble("received", (values[0][0]));
|
||||||
params.putDouble("totalRead", (values[0][1]));
|
params.putDouble("total", (values[0][1]));
|
||||||
params.putDouble("contentLength", (values[0][2]));
|
params.putString("hashname", this.hash);
|
||||||
sendEvent("progress", params);
|
sendEvent("RCTPushyDownloadProgress", params);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,7 +238,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void doDownload(DownloadTaskParams param) throws IOException {
|
private void doDownload(DownloadTaskParams param) throws IOException {
|
||||||
downloadFile(param.url, param.zipFilePath);
|
downloadFile(param);
|
||||||
|
|
||||||
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
||||||
ZipEntry ze;
|
ZipEntry ze;
|
||||||
@@ -295,7 +295,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void doPatchFromApk(DownloadTaskParams param) throws IOException, JSONException {
|
private void doPatchFromApk(DownloadTaskParams param) throws IOException, JSONException {
|
||||||
downloadFile(param.url, param.zipFilePath);
|
downloadFile(param);
|
||||||
|
|
||||||
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
||||||
ZipEntry ze;
|
ZipEntry ze;
|
||||||
@@ -371,7 +371,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void doPatchFromPpk(DownloadTaskParams param) throws IOException, JSONException {
|
private void doPatchFromPpk(DownloadTaskParams param) throws IOException, JSONException {
|
||||||
downloadFile(param.url, param.zipFilePath);
|
downloadFile(param);
|
||||||
|
|
||||||
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
|
||||||
ZipEntry ze;
|
ZipEntry ze;
|
||||||
|
@@ -7,6 +7,8 @@ import android.content.pm.PackageManager;
|
|||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
import com.facebook.react.ReactInstanceManager;
|
import com.facebook.react.ReactInstanceManager;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
@@ -23,6 +25,7 @@ public class UpdateContext {
|
|||||||
|
|
||||||
public static boolean DEBUG = false;
|
public static boolean DEBUG = false;
|
||||||
private static ReactInstanceManager mReactInstanceManager;
|
private static ReactInstanceManager mReactInstanceManager;
|
||||||
|
private static boolean isUsingBundleUrl = false;
|
||||||
|
|
||||||
public UpdateContext(Context context) {
|
public UpdateContext(Context context) {
|
||||||
this.context = context;
|
this.context = context;
|
||||||
@@ -67,6 +70,21 @@ public class UpdateContext {
|
|||||||
return context.getString(R.string.pushy_build_time);
|
return context.getString(R.string.pushy_build_time);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getUuid() {
|
||||||
|
return sp.getString("uuid", null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map getBlockUpdate() {
|
||||||
|
return new HashMap<String, Object>() {{
|
||||||
|
put("until", sp.getInt("blockUntil", 0));
|
||||||
|
put("reason", sp.getString("blockReason", null));
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean getIsUsingBundleUrl() {
|
||||||
|
return isUsingBundleUrl;
|
||||||
|
}
|
||||||
|
|
||||||
public interface DownloadFileListener {
|
public interface DownloadFileListener {
|
||||||
void onDownloadCompleted();
|
void onDownloadCompleted();
|
||||||
void onDownloadFailed(Throwable error);
|
void onDownloadFailed(Throwable error);
|
||||||
@@ -125,6 +143,19 @@ public class UpdateContext {
|
|||||||
editor.apply();
|
editor.apply();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void setUuid(String uuid) {
|
||||||
|
SharedPreferences.Editor editor = sp.edit();
|
||||||
|
editor.putString("uuid", uuid);
|
||||||
|
editor.apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBlockUpdate(int until, String reason) {
|
||||||
|
SharedPreferences.Editor editor = sp.edit();
|
||||||
|
editor.putInt("blockUntil", until);
|
||||||
|
editor.putString("blockReason", reason);
|
||||||
|
editor.apply();
|
||||||
|
}
|
||||||
|
|
||||||
public String getCurrentVersion() {
|
public String getCurrentVersion() {
|
||||||
return sp.getString("currentVersion", null);
|
return sp.getString("currentVersion", null);
|
||||||
}
|
}
|
||||||
@@ -184,6 +215,7 @@ public class UpdateContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public String getBundleUrl(String defaultAssetsUrl) {
|
public String getBundleUrl(String defaultAssetsUrl) {
|
||||||
|
isUsingBundleUrl = true;
|
||||||
String currentVersion = getCurrentVersion();
|
String currentVersion = getCurrentVersion();
|
||||||
if (currentVersion == null) {
|
if (currentVersion == null) {
|
||||||
return defaultAssetsUrl;
|
return defaultAssetsUrl;
|
||||||
|
@@ -46,6 +46,7 @@ public class UpdateModule extends ReactContextBaseJavaModule{
|
|||||||
constants.put("packageVersion", updateContext.getPackageVersion());
|
constants.put("packageVersion", updateContext.getPackageVersion());
|
||||||
constants.put("currentVersion", updateContext.getCurrentVersion());
|
constants.put("currentVersion", updateContext.getCurrentVersion());
|
||||||
constants.put("buildTime", updateContext.getBuildTime());
|
constants.put("buildTime", updateContext.getBuildTime());
|
||||||
|
constants.put("isUsingBundleUrl", updateContext.getIsUsingBundleUrl());
|
||||||
boolean isFirstTime = updateContext.isFirstTime();
|
boolean isFirstTime = updateContext.isFirstTime();
|
||||||
constants.put("isFirstTime", isFirstTime);
|
constants.put("isFirstTime", isFirstTime);
|
||||||
if (isFirstTime) {
|
if (isFirstTime) {
|
||||||
@@ -56,6 +57,8 @@ public class UpdateModule extends ReactContextBaseJavaModule{
|
|||||||
if (isRolledBack) {
|
if (isRolledBack) {
|
||||||
updateContext.clearRollbackMark();
|
updateContext.clearRollbackMark();
|
||||||
}
|
}
|
||||||
|
constants.put("blockUpdate", updateContext.getBlockUpdate());
|
||||||
|
constants.put("uuid", updateContext.getUuid());
|
||||||
return constants;
|
return constants;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,14 +137,14 @@ public class UpdateModule extends ReactContextBaseJavaModule{
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Field jsBundleField = instanceManager.getClass().getDeclaredField("mJSBundleFile");
|
|
||||||
jsBundleField.setAccessible(true);
|
|
||||||
jsBundleField.set(instanceManager, UpdateContext.getBundleUrl(application));
|
|
||||||
} catch (Throwable err) {
|
|
||||||
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
|
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
|
||||||
Field loadField = instanceManager.getClass().getDeclaredField("mBundleLoader");
|
Field loadField = instanceManager.getClass().getDeclaredField("mBundleLoader");
|
||||||
loadField.setAccessible(true);
|
loadField.setAccessible(true);
|
||||||
loadField.set(instanceManager, loader);
|
loadField.set(instanceManager, loader);
|
||||||
|
} catch (Throwable err) {
|
||||||
|
Field jsBundleField = instanceManager.getClass().getDeclaredField("mJSBundleFile");
|
||||||
|
jsBundleField.setAccessible(true);
|
||||||
|
jsBundleField.set(instanceManager, UpdateContext.getBundleUrl(application));
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -183,6 +186,28 @@ public class UpdateModule extends ReactContextBaseJavaModule{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ReactMethod
|
||||||
|
public void setBlockUpdate(ReadableMap options) {
|
||||||
|
final int until = options.getInt("until");
|
||||||
|
final String reason = options.getString("reason");
|
||||||
|
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
updateContext.setBlockUpdate(until, reason);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@ReactMethod
|
||||||
|
public void setUuid(final String uuid) {
|
||||||
|
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
updateContext.setUuid(uuid);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/* 发送事件*/
|
/* 发送事件*/
|
||||||
public static void sendEvent(String eventName, WritableMap params) {
|
public static void sendEvent(String eventName, WritableMap params) {
|
||||||
((ReactContext) mContext).getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName,
|
((ReactContext) mContext).getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName,
|
||||||
|
1
endpoints.json
Normal file
1
endpoints.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
["https://update.react-native.cn/api", "https://update.reactnative.cn/api"]
|
@@ -27,6 +27,8 @@ static NSString *const paramLastVersion = @"lastVersion";
|
|||||||
static NSString *const paramCurrentVersion = @"currentVersion";
|
static NSString *const paramCurrentVersion = @"currentVersion";
|
||||||
static NSString *const paramIsFirstTime = @"isFirstTime";
|
static NSString *const paramIsFirstTime = @"isFirstTime";
|
||||||
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
|
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
|
||||||
|
static NSString *const keyBlockUpdate = @"REACTNATIVECN_PUSHY_BLOCKUPDATE";
|
||||||
|
static NSString *const keyUuid = @"REACTNATIVECN_PUSHY_UUID";
|
||||||
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
|
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
|
||||||
static NSString *const keyRolledBackMarked = @"REACTNATIVECN_PUSHY_ROLLEDBACKMARKED_KEY";
|
static NSString *const keyRolledBackMarked = @"REACTNATIVECN_PUSHY_ROLLEDBACKMARKED_KEY";
|
||||||
static NSString *const KeyPackageUpdatedMarked = @"REACTNATIVECN_PUSHY_ISPACKAGEUPDATEDMARKED_KEY";
|
static NSString *const KeyPackageUpdatedMarked = @"REACTNATIVECN_PUSHY_ISPACKAGEUPDATEDMARKED_KEY";
|
||||||
@@ -93,10 +95,10 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
BOOL isFirstTime = [pushyInfo[paramIsFirstTime] boolValue];
|
BOOL isFirstTime = [pushyInfo[paramIsFirstTime] boolValue];
|
||||||
BOOL isFirstLoadOK = [pushyInfo[paramIsFirstLoadOk] boolValue];
|
BOOL isFirstLoadOK = [pushyInfo[paramIsFirstLoadOk] boolValue];
|
||||||
|
|
||||||
NSString *loadVersioin = curVersion;
|
NSString *loadVersion = curVersion;
|
||||||
BOOL needRollback = (!ignoreRollback && isFirstTime == NO && isFirstLoadOK == NO) || loadVersioin.length<=0;
|
BOOL needRollback = (!ignoreRollback && isFirstTime == NO && isFirstLoadOK == NO) || loadVersion.length<=0;
|
||||||
if (needRollback) {
|
if (needRollback) {
|
||||||
loadVersioin = lastVersion;
|
loadVersion = lastVersion;
|
||||||
|
|
||||||
if (lastVersion.length) {
|
if (lastVersion.length) {
|
||||||
// roll back to last version
|
// roll back to last version
|
||||||
@@ -125,10 +127,10 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
[defaults synchronize];
|
[defaults synchronize];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (loadVersioin.length) {
|
if (loadVersion.length) {
|
||||||
NSString *downloadDir = [RCTPushy downloadDir];
|
NSString *downloadDir = [RCTPushy downloadDir];
|
||||||
|
|
||||||
NSString *bundlePath = [[downloadDir stringByAppendingPathComponent:loadVersioin] stringByAppendingPathComponent:BUNDLE_FILE_NAME];
|
NSString *bundlePath = [[downloadDir stringByAppendingPathComponent:loadVersion] stringByAppendingPathComponent:BUNDLE_FILE_NAME];
|
||||||
if ([[NSFileManager defaultManager] fileExistsAtPath:bundlePath isDirectory:NULL]) {
|
if ([[NSFileManager defaultManager] fileExistsAtPath:bundlePath isDirectory:NULL]) {
|
||||||
NSURL *bundleURL = [NSURL fileURLWithPath:bundlePath];
|
NSURL *bundleURL = [NSURL fileURLWithPath:bundlePath];
|
||||||
return bundleURL;
|
return bundleURL;
|
||||||
@@ -155,6 +157,8 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
ret[@"buildTime"] = [RCTPushy buildTime];
|
ret[@"buildTime"] = [RCTPushy buildTime];
|
||||||
ret[@"isRolledBack"] = [defaults objectForKey:keyRolledBackMarked];
|
ret[@"isRolledBack"] = [defaults objectForKey:keyRolledBackMarked];
|
||||||
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
|
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
|
||||||
|
ret[@"blockUpdate"] = [defaults objectForKey:keyBlockUpdate];
|
||||||
|
ret[@"uuid"] = [defaults objectForKey:keyUuid];
|
||||||
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
|
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
|
||||||
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
|
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
|
||||||
|
|
||||||
@@ -188,6 +192,23 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
RCT_EXPORT_METHOD(setBlockUpdate:(NSDictionary *)options)
|
||||||
|
{
|
||||||
|
// NSMutableDictionary *blockUpdateInfo = [NSMutableDictionary new];
|
||||||
|
// blockUpdateInfo[@"reason"] = options[@"reason"];
|
||||||
|
// blockUpdateInfo[@"until"] = options[@"until"];
|
||||||
|
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
||||||
|
[defaults setObject:options forKey:keyBlockUpdate];
|
||||||
|
[defaults synchronize];
|
||||||
|
}
|
||||||
|
|
||||||
|
RCT_EXPORT_METHOD(setUuid:(NSString *)uuid)
|
||||||
|
{
|
||||||
|
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
||||||
|
[defaults setObject:uuid forKey:keyUuid];
|
||||||
|
[defaults synchronize];
|
||||||
|
}
|
||||||
|
|
||||||
RCT_EXPORT_METHOD(downloadUpdate:(NSDictionary *)options
|
RCT_EXPORT_METHOD(downloadUpdate:(NSDictionary *)options
|
||||||
resolver:(RCTPromiseResolveBlock)resolve
|
resolver:(RCTPromiseResolveBlock)resolve
|
||||||
rejecter:(RCTPromiseRejectBlock)reject)
|
rejecter:(RCTPromiseRejectBlock)reject)
|
||||||
@@ -302,7 +323,7 @@ RCT_EXPORT_METHOD(markSuccess)
|
|||||||
callback([self errorWithMessage:ERROR_FILE_OPERATION]);
|
callback([self errorWithMessage:ERROR_FILE_OPERATION]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *zipFilePath = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",hashName, [self zipExtension:type]]];
|
NSString *zipFilePath = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",hashName, [self zipExtension:type]]];
|
||||||
NSString *unzipDir = [dir stringByAppendingPathComponent:hashName];
|
NSString *unzipDir = [dir stringByAppendingPathComponent:hashName];
|
||||||
|
|
||||||
|
89
lib/endpoint.js
Normal file
89
lib/endpoint.js
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
let currentEndpoint = 'https://update.react-native.cn/api';
|
||||||
|
|
||||||
|
function ping(url, rejectImmediate) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
xhr.onreadystatechange = (e) => {
|
||||||
|
if (xhr.readyState !== 4) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (xhr.status === 200) {
|
||||||
|
resolve(url);
|
||||||
|
} else {
|
||||||
|
rejectImmediate ? reject() : setTimeout(reject, 5000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
xhr.open('HEAD', url);
|
||||||
|
xhr.send();
|
||||||
|
xhr.timeout = 5000;
|
||||||
|
xhr.ontimeout = reject;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function logger(...args) {
|
||||||
|
// console.warn('pushy', ...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
let backupEndpoints = [];
|
||||||
|
let backupEndpointsQueryUrl =
|
||||||
|
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json';
|
||||||
|
|
||||||
|
export async function tryBackupEndpoints() {
|
||||||
|
if (!backupEndpoints.length && !backupEndpointsQueryUrl) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await ping(getStatusUrl(), true);
|
||||||
|
logger('current endpoint ok');
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
logger('current endpoint failed');
|
||||||
|
}
|
||||||
|
if (!backupEndpoints.length && backupEndpointsQueryUrl) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(backupEndpointsQueryUrl);
|
||||||
|
backupEndpoints = await resp.json();
|
||||||
|
logger('get remote endpoints:', backupEndpoints);
|
||||||
|
} catch (e) {
|
||||||
|
logger('get remote endpoints failed');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await pickFatestAvailableEndpoint();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickFatestAvailableEndpoint(endpoints = backupEndpoints) {
|
||||||
|
const fastestEndpoint = await Promise.race(
|
||||||
|
endpoints.map(pingAndReturnEndpoint),
|
||||||
|
);
|
||||||
|
if (typeof fastestEndpoint === 'string') {
|
||||||
|
logger(`pick endpoint: ${fastestEndpoint}`);
|
||||||
|
currentEndpoint = fastestEndpoint;
|
||||||
|
} else {
|
||||||
|
logger('all remote endpoints failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pingAndReturnEndpoint(endpoint = currentEndpoint) {
|
||||||
|
return ping(getStatusUrl(endpoint)).then(() => endpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getStatusUrl(endpoint = currentEndpoint) {
|
||||||
|
return `${endpoint}/status`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
|
||||||
|
return `${endpoint}/checkUpdate/${APPKEY}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCustomEndpoints({ main, backups, backupQueryUrl }) {
|
||||||
|
currentEndpoint = main;
|
||||||
|
backupEndpointsQueryUrl = null;
|
||||||
|
if (Array.isArray(backups) && backups.length > 0) {
|
||||||
|
backupEndpoints = backups;
|
||||||
|
pickFatestAvailableEndpoint();
|
||||||
|
}
|
||||||
|
if (typeof backupQueryUrl === 'string') {
|
||||||
|
backupEndpointsQueryUrl = backupQueryUrl;
|
||||||
|
}
|
||||||
|
}
|
@@ -1,57 +0,0 @@
|
|||||||
let availableDomain = 'update.react-native.cn';
|
|
||||||
|
|
||||||
function ping(domain, rejectImmediate) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const xhr = new XMLHttpRequest();
|
|
||||||
xhr.onreadystatechange = e => {
|
|
||||||
if (xhr.readyState !== 4) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (xhr.status === 200) {
|
|
||||||
resolve(domain);
|
|
||||||
} else {
|
|
||||||
rejectImmediate ? reject() : setTimeout(reject, 5000);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
xhr.open('HEAD', `https://${domain}`);
|
|
||||||
xhr.send();
|
|
||||||
xhr.timeout = 5000;
|
|
||||||
xhr.ontimeout = reject;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function logger(...args) {
|
|
||||||
// console.warn('pushy', ...args);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function tryBackupDomains() {
|
|
||||||
try {
|
|
||||||
await ping(availableDomain, true);
|
|
||||||
logger('main domain ok');
|
|
||||||
return;
|
|
||||||
} catch (e) {
|
|
||||||
logger('main domain failed');
|
|
||||||
}
|
|
||||||
let backupDomains = [];
|
|
||||||
try {
|
|
||||||
const resp = await fetch(
|
|
||||||
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/domains.json',
|
|
||||||
);
|
|
||||||
backupDomains = await resp.json();
|
|
||||||
logger('get remote domains:', backupDomains);
|
|
||||||
} catch (e) {
|
|
||||||
logger('get remote domains failed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const fastestDomain = await Promise.race(backupDomains.map(ping));
|
|
||||||
if (typeof fastestDomain === 'string') {
|
|
||||||
logger(`pick domain: ${fastestDomain}`);
|
|
||||||
availableDomain = fastestDomain;
|
|
||||||
} else {
|
|
||||||
logger('all remote domains failed');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function getHost() {
|
|
||||||
return `https://${availableDomain}/api`;
|
|
||||||
}
|
|
33
lib/index.d.ts
vendored
33
lib/index.d.ts
vendored
@@ -20,17 +20,44 @@ export interface UpdateAvailableResult {
|
|||||||
description: string;
|
description: string;
|
||||||
metaInfo: string;
|
metaInfo: string;
|
||||||
pdiffUrl: string;
|
pdiffUrl: string;
|
||||||
diffUrl: string;
|
diffUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CheckResult = Partial<ExpiredResult & UpTodateResult & UpdateAvailableResult>;
|
export type CheckResult =
|
||||||
|
| ExpiredResult
|
||||||
|
| UpTodateResult
|
||||||
|
| UpdateAvailableResult;
|
||||||
|
|
||||||
export function checkUpdate(appkey: string): Promise<CheckResult>;
|
export function checkUpdate(appkey: string): Promise<CheckResult>;
|
||||||
|
|
||||||
export function downloadUpdate(options: UpdateAvailableResult): Promise<undefined | string>;
|
export function downloadUpdate(
|
||||||
|
options: UpdateAvailableResult,
|
||||||
|
): Promise<undefined | string>;
|
||||||
|
|
||||||
export function switchVersion(hash: string): void;
|
export function switchVersion(hash: string): void;
|
||||||
|
|
||||||
export function switchVersionLater(hash: string): void;
|
export function switchVersionLater(hash: string): void;
|
||||||
|
|
||||||
export function markSuccess(): void;
|
export function markSuccess(): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} main - The main api endpoint
|
||||||
|
* @param {string[]} [backups] - The back up endpoints.
|
||||||
|
* @param {string} [backupQueryUrl] - An url that return a json file containing an array of endpoint.
|
||||||
|
* like: ["https://backup.api/1", "https://backup.api/2"]
|
||||||
|
*/
|
||||||
|
export function setCustomEndpoints({
|
||||||
|
main,
|
||||||
|
backups,
|
||||||
|
backupQueryUrl,
|
||||||
|
}: {
|
||||||
|
main: string;
|
||||||
|
backUps?: string[];
|
||||||
|
backupQueryUrl?: string;
|
||||||
|
}): void;
|
||||||
|
|
||||||
|
|
||||||
|
interface ProgressEvent {
|
||||||
|
received: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
84
lib/index.js
84
lib/index.js
@@ -1,5 +1,15 @@
|
|||||||
import getHost, { tryBackupDomains } from './getHost';
|
import {
|
||||||
import { NativeAppEventEmitter, NativeModules } from 'react-native';
|
tryBackupEndpoints,
|
||||||
|
getCheckUrl,
|
||||||
|
setCustomEndpoints,
|
||||||
|
} from './endpoint';
|
||||||
|
import { NativeAppEventEmitter, NativeModules, Platform } from 'react-native';
|
||||||
|
export { setCustomEndpoints };
|
||||||
|
const {
|
||||||
|
version: v,
|
||||||
|
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||||
|
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
||||||
|
const uuidv4 = require('uuid/v4');
|
||||||
|
|
||||||
let Pushy = NativeModules.Pushy;
|
let Pushy = NativeModules.Pushy;
|
||||||
|
|
||||||
@@ -13,10 +23,25 @@ export const currentVersion = Pushy.currentVersion;
|
|||||||
export const isFirstTime = Pushy.isFirstTime;
|
export const isFirstTime = Pushy.isFirstTime;
|
||||||
export const isRolledBack = Pushy.isRolledBack;
|
export const isRolledBack = Pushy.isRolledBack;
|
||||||
export const buildTime = Pushy.buildTime;
|
export const buildTime = Pushy.buildTime;
|
||||||
|
let blockUpdate = Pushy.blockUpdate;
|
||||||
|
let uuid = Pushy.uuid;
|
||||||
|
|
||||||
|
if (Platform.OS === 'android' && !Pushy.isUsingBundleUrl) {
|
||||||
|
throw new Error(
|
||||||
|
'react-native-update模块无法加载,请对照文档检查Bundle URL的配置',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!uuid) {
|
||||||
|
uuid = uuidv4();
|
||||||
|
Pushy.setUuid(uuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Pushy uuid: ' + uuid);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Return json:
|
Return json:
|
||||||
Package was expired:
|
Package expired:
|
||||||
{
|
{
|
||||||
expired: true,
|
expired: true,
|
||||||
downloadUrl: 'http://appstore/downloadUrl',
|
downloadUrl: 'http://appstore/downloadUrl',
|
||||||
@@ -45,9 +70,16 @@ function assertRelease() {
|
|||||||
|
|
||||||
export async function checkUpdate(APPKEY, isRetry) {
|
export async function checkUpdate(APPKEY, isRetry) {
|
||||||
assertRelease();
|
assertRelease();
|
||||||
|
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
|
||||||
|
throw new Error(
|
||||||
|
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
|
||||||
|
blockUpdate.until * 1000,
|
||||||
|
).toLocaleString()}"之后重试。`,
|
||||||
|
);
|
||||||
|
}
|
||||||
let resp;
|
let resp;
|
||||||
try {
|
try {
|
||||||
resp = await fetch(`${getHost()}/checkUpdate/${APPKEY}`, {
|
resp = await fetch(getCheckUrl(APPKEY), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
Accept: 'application/json',
|
Accept: 'application/json',
|
||||||
@@ -57,21 +89,44 @@ export async function checkUpdate(APPKEY, isRetry) {
|
|||||||
packageVersion,
|
packageVersion,
|
||||||
hash: currentVersion,
|
hash: currentVersion,
|
||||||
buildTime,
|
buildTime,
|
||||||
|
cInfo: {
|
||||||
|
pushy: require('../package.json').version,
|
||||||
|
rn: RNVersion,
|
||||||
|
os: Platform.OS + ' ' + Platform.Version,
|
||||||
|
uuid,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isRetry) {
|
if (isRetry) {
|
||||||
throw new Error('Could not connect to pushy server');
|
throw new Error('Could not connect to pushy server');
|
||||||
}
|
}
|
||||||
await tryBackupDomains();
|
await tryBackupEndpoints(APPKEY);
|
||||||
return checkUpdate(APPKEY, true);
|
return checkUpdate(APPKEY, true);
|
||||||
}
|
}
|
||||||
|
const result = await resp.json();
|
||||||
|
checkOperation(result.op);
|
||||||
|
|
||||||
if (resp.status !== 200) {
|
if (resp.status !== 200) {
|
||||||
throw new Error((await resp.json()).message);
|
throw new Error(result.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
return resp.json();
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkOperation(op) {
|
||||||
|
if (!Array.isArray(op)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
op.forEach((action) => {
|
||||||
|
if (action.type === 'block') {
|
||||||
|
blockUpdate = {
|
||||||
|
reason: action.reason,
|
||||||
|
until: (Date.now() + action.duration) / 1000,
|
||||||
|
};
|
||||||
|
Pushy.setBlockUpdate(blockUpdate);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function downloadUpdate(options) {
|
export async function downloadUpdate(options) {
|
||||||
@@ -79,7 +134,6 @@ export async function downloadUpdate(options) {
|
|||||||
if (!options.update) {
|
if (!options.update) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.diffUrl) {
|
if (options.diffUrl) {
|
||||||
await Pushy.downloadPatchFromPpk({
|
await Pushy.downloadPatchFromPpk({
|
||||||
updateUrl: options.diffUrl,
|
updateUrl: options.diffUrl,
|
||||||
@@ -91,11 +145,6 @@ export async function downloadUpdate(options) {
|
|||||||
updateUrl: options.pdiffUrl,
|
updateUrl: options.pdiffUrl,
|
||||||
hashName: options.hash,
|
hashName: options.hash,
|
||||||
});
|
});
|
||||||
} else {
|
|
||||||
await Pushy.downloadUpdate({
|
|
||||||
updateUrl: options.updateUrl,
|
|
||||||
hashName: options.hash,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
return options.hash;
|
return options.hash;
|
||||||
}
|
}
|
||||||
@@ -115,11 +164,6 @@ export function markSuccess() {
|
|||||||
Pushy.markSuccess();
|
Pushy.markSuccess();
|
||||||
}
|
}
|
||||||
|
|
||||||
// function report(action) {
|
NativeAppEventEmitter.addListener('RCTPushyDownloadProgress', (params) => {});
|
||||||
// // ${project}.${host}/logstores/${logstore}/track?APIVersion=0.6.0&key1=val1
|
|
||||||
// fetch(`${logUrl}&action=${action}`);
|
|
||||||
// }
|
|
||||||
|
|
||||||
NativeAppEventEmitter.addListener('RCTPushyDownloadProgress', params => {});
|
NativeAppEventEmitter.addListener('RCTPushyUnzipProgress', (params) => {});
|
||||||
|
|
||||||
NativeAppEventEmitter.addListener('RCTPushyUnzipProgress', params => {});
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "react-native-update",
|
"name": "react-native-update",
|
||||||
"version": "5.6.0",
|
"version": "5.7.2",
|
||||||
"description": "react-native hot update",
|
"description": "react-native hot update",
|
||||||
"main": "lib/index.js",
|
"main": "lib/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -26,5 +26,7 @@
|
|||||||
"react-native": ">=0.27.0"
|
"react-native": ">=0.27.0"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
||||||
"dependencies": {}
|
"dependencies": {
|
||||||
|
"uuid": "3"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user