1
0
mirror of https://gitcode.com/gh_mirrors/re/react-native-pushy.git synced 2025-09-18 01:26:10 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

10 Commits

Author SHA1 Message Date
sunnylqm
ebb5defb10 v5.7.2 2020-09-01 10:51:43 +08:00
sunnylqm
a509ff8e30 Cleanup 2020-09-01 10:51:15 +08:00
sunnylqm
59fcba15ee Implement blockupdate on android 2020-08-31 18:39:03 +08:00
sunnylqm
c6f9bb20a1 Add client info and uuid 2020-08-31 11:47:08 +08:00
sunnylqm
9e6c7ea769 setBlockUpdate 2020-08-31 01:17:28 +08:00
sunnylqm
f461c8ddd2 Update endpoint and example 2020-08-26 00:44:34 +08:00
sunnylqm
4cbeb7bec4 v5.7.0 2020-08-13 00:32:52 +08:00
sunnylqm
ed7f5ac606 Detect android bundle url 2020-08-13 00:32:07 +08:00
sunnylqm
6abb2c7a5d Unify download progress event 2020-08-09 00:08:30 +08:00
sunnylqm
a4a372f17e Revert "Exclude backup"
This reverts commit 2d805fb38e.
2020-08-08 21:09:15 +08:00
13 changed files with 210 additions and 2678 deletions

7
.gitignore vendored
View File

@@ -1,7 +1,6 @@
/.idea
/node_modules
/android/build
/android/obj
.vscode
android/build
android/obj
*.iml
# OSX

View File

@@ -1,11 +1,11 @@
/.idea
/.babelrc
/.npmignore
/.eslintrc
/.nvmrc
/.travis.yml
/Example
/android/build
.babelrc
.npmignore
.eslintrc
.nvmrc
.travis.yml
Example
android/build
.vscode
# OSX
#
@@ -45,4 +45,5 @@ Example
yarn.lock
android/jni
domains.json
domains.json
endpoints.json

View File

@@ -52,36 +52,34 @@ export default class App extends Component {
}
}
doUpdate = async info => {
const hash = await downloadUpdate(info);
Alert.alert('提示', '下载完毕,是否重启应用?', [
{
text: '是',
onPress: () => {
switchVersion(hash);
try {
const hash = await downloadUpdate(info);
Alert.alert('提示', '下载完毕,是否重启应用?', [
{
text: '是',
onPress: () => {
switchVersion(hash);
},
},
},
{text: '否'},
{
text: '下次启动时',
onPress: () => {
switchVersionLater(hash);
{text: '否'},
{
text: '下次启动时',
onPress: () => {
switchVersionLater(hash);
},
},
},
]);
]);
} catch (err) {
Alert.alert('更新失败', err.message);
}
};
checkUpdate = async () => {
return await this.doUpdate({
update: true,
pdiffUrl: 'http://localhost:8888/1.pdiff',
hash: 'test',
});
let info;
try {
info = await checkUpdate(appKey);
} catch (err) {
console.warn(err);
Alert.alert('更新检查失败', err.message);
return;
}
if (info.expired) {
@@ -115,7 +113,7 @@ export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>443欢迎使用热更新服务</Text>
<Text style={styles.welcome}>欢迎使用热更新服务</Text>
<Image
resizeMode={'contain'}
source={require('./assets/shezhi.png')}

View File

@@ -41,6 +41,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
final int DOWNLOAD_CHUNK_SIZE = 4096;
Context context;
String hash;
DownloadTask(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();
Request request = new Request.Builder().url(url)
.build();
@@ -92,21 +96,17 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
}
long bytesRead = 0;
long totalRead = 0;
double lastProgressValue=0;
long received = 0;
while ((bytesRead = source.read(sink.buffer(), DOWNLOAD_CHUNK_SIZE)) != -1) {
totalRead += bytesRead;
received += bytesRead;
sink.emit();
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Progress " + totalRead + "/" + contentLength);
}
double progress = Math.round(((double) totalRead * 100) / contentLength);
if ((progress != lastProgressValue) || (totalRead == contentLength)) {
lastProgressValue = progress;
publishProgress(new long[]{(long)progress,totalRead, contentLength});
Log.d("RNUpdate", "Progress " + received + "/" + contentLength);
}
publishProgress(new long[]{received, contentLength});
}
if (totalRead != contentLength) {
if (received != contentLength) {
throw new Error("Unexpected eof while reading ppk");
}
sink.writeAll(source);
@@ -121,10 +121,10 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
protected void onProgressUpdate(long[]... values) {
super.onProgressUpdate(values);
WritableMap params = Arguments.createMap();
params.putDouble("progress", (values[0][0]));
params.putDouble("totalRead", (values[0][1]));
params.putDouble("contentLength", (values[0][2]));
sendEvent("progress", params);
params.putDouble("received", (values[0][0]));
params.putDouble("total", (values[0][1]));
params.putString("hashname", this.hash);
sendEvent("RCTPushyDownloadProgress", params);
}
@@ -238,7 +238,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
}
private void doDownload(DownloadTaskParams param) throws IOException {
downloadFile(param.url, param.zipFilePath);
downloadFile(param);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(param.zipFilePath)));
ZipEntry ze;
@@ -295,7 +295,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
}
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)));
ZipEntry ze;
@@ -371,7 +371,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
}
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)));
ZipEntry ze;

View File

@@ -7,6 +7,8 @@ import android.content.pm.PackageManager;
import android.util.Log;
import com.facebook.react.ReactInstanceManager;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@@ -23,6 +25,7 @@ public class UpdateContext {
public static boolean DEBUG = false;
private static ReactInstanceManager mReactInstanceManager;
private static boolean isUsingBundleUrl = false;
public UpdateContext(Context context) {
this.context = context;
@@ -67,6 +70,21 @@ public class UpdateContext {
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 {
void onDownloadCompleted();
void onDownloadFailed(Throwable error);
@@ -125,6 +143,19 @@ public class UpdateContext {
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() {
return sp.getString("currentVersion", null);
}
@@ -184,6 +215,7 @@ public class UpdateContext {
}
public String getBundleUrl(String defaultAssetsUrl) {
isUsingBundleUrl = true;
String currentVersion = getCurrentVersion();
if (currentVersion == null) {
return defaultAssetsUrl;

View File

@@ -46,6 +46,7 @@ public class UpdateModule extends ReactContextBaseJavaModule{
constants.put("packageVersion", updateContext.getPackageVersion());
constants.put("currentVersion", updateContext.getCurrentVersion());
constants.put("buildTime", updateContext.getBuildTime());
constants.put("isUsingBundleUrl", updateContext.getIsUsingBundleUrl());
boolean isFirstTime = updateContext.isFirstTime();
constants.put("isFirstTime", isFirstTime);
if (isFirstTime) {
@@ -56,6 +57,8 @@ public class UpdateModule extends ReactContextBaseJavaModule{
if (isRolledBack) {
updateContext.clearRollbackMark();
}
constants.put("blockUpdate", updateContext.getBlockUpdate());
constants.put("uuid", updateContext.getUuid());
return constants;
}
@@ -134,14 +137,14 @@ public class UpdateModule extends ReactContextBaseJavaModule{
}
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));
Field loadField = instanceManager.getClass().getDeclaredField("mBundleLoader");
loadField.setAccessible(true);
loadField.set(instanceManager, loader);
} catch (Throwable err) {
Field jsBundleField = instanceManager.getClass().getDeclaredField("mJSBundleFile");
jsBundleField.setAccessible(true);
jsBundleField.set(instanceManager, UpdateContext.getBundleUrl(application));
}
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) {
((ReactContext) mContext).getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName,

View File

@@ -27,6 +27,8 @@ static NSString *const paramLastVersion = @"lastVersion";
static NSString *const paramCurrentVersion = @"currentVersion";
static NSString *const paramIsFirstTime = @"isFirstTime";
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 keyRolledBackMarked = @"REACTNATIVECN_PUSHY_ROLLEDBACKMARKED_KEY";
static NSString *const KeyPackageUpdatedMarked = @"REACTNATIVECN_PUSHY_ISPACKAGEUPDATEDMARKED_KEY";
@@ -155,6 +157,8 @@ RCT_EXPORT_MODULE(RCTPushy);
ret[@"buildTime"] = [RCTPushy buildTime];
ret[@"isRolledBack"] = [defaults objectForKey:keyRolledBackMarked];
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
ret[@"blockUpdate"] = [defaults objectForKey:keyBlockUpdate];
ret[@"uuid"] = [defaults objectForKey:keyUuid];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
@@ -188,6 +192,23 @@ RCT_EXPORT_MODULE(RCTPushy);
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
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)

View File

@@ -24,21 +24,6 @@
return self;
}
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
NSURL* URL= [NSURL fileURLWithPath: filePathString];
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
}
return success;
}
- (BOOL)createDir:(NSString *)dir
{
__block BOOL success = false;
@@ -63,7 +48,7 @@
return;
}
});
[self addSkipBackupAttributeToItemAtPath:dir];
return success;
}

View File

@@ -1,4 +1,4 @@
let currentEndpoint = 'https://update.reactnative.cn/api';
let currentEndpoint = 'https://update.react-native.cn/api';
function ping(url, rejectImmediate) {
return new Promise((resolve, reject) => {

6
lib/index.d.ts vendored
View File

@@ -55,3 +55,9 @@ export function setCustomEndpoints({
backUps?: string[];
backupQueryUrl?: string;
}): void;
interface ProgressEvent {
received: number;
total: number;
}

View File

@@ -1,6 +1,15 @@
import { tryBackupEndpoints, getCheckUrl, setCustomEndpoints } from './endpoint';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
import {
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;
@@ -14,10 +23,25 @@ export const currentVersion = Pushy.currentVersion;
export const isFirstTime = Pushy.isFirstTime;
export const isRolledBack = Pushy.isRolledBack;
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:
Package was expired:
Package expired:
{
expired: true,
downloadUrl: 'http://appstore/downloadUrl',
@@ -46,6 +70,13 @@ function assertRelease() {
export async function checkUpdate(APPKEY, isRetry) {
assertRelease();
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
throw new Error(
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"之后重试。`,
);
}
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), {
@@ -58,6 +89,12 @@ export async function checkUpdate(APPKEY, isRetry) {
packageVersion,
hash: currentVersion,
buildTime,
cInfo: {
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,
},
}),
});
} catch (e) {
@@ -67,12 +104,29 @@ export async function checkUpdate(APPKEY, isRetry) {
await tryBackupEndpoints(APPKEY);
return checkUpdate(APPKEY, true);
}
const result = await resp.json();
checkOperation(result.op);
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) {
@@ -80,7 +134,6 @@ export async function downloadUpdate(options) {
if (!options.update) {
return;
}
if (options.diffUrl) {
await Pushy.downloadPatchFromPpk({
updateUrl: options.diffUrl,
@@ -111,11 +164,6 @@ export function markSuccess() {
Pushy.markSuccess();
}
// function report(action) {
// // ${project}.${host}/logstores/${logstore}/track?APIVersion=0.6.0&key1=val1
// fetch(`${logUrl}&action=${action}`);
// }
NativeAppEventEmitter.addListener('RCTPushyDownloadProgress', (params) => {});
NativeAppEventEmitter.addListener('RCTPushyDownloadProgress', params => {});
NativeAppEventEmitter.addListener('RCTPushyUnzipProgress', params => {});
NativeAppEventEmitter.addListener('RCTPushyUnzipProgress', (params) => {});

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "5.7.0-beta1",
"version": "5.7.2",
"description": "react-native hot update",
"main": "lib/index.js",
"scripts": {
@@ -26,5 +26,7 @@
"react-native": ">=0.27.0"
},
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
"dependencies": {}
"dependencies": {
"uuid": "3"
}
}

2593
yarn.lock

File diff suppressed because it is too large Load Diff