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

Compare commits

..

9 Commits

Author SHA1 Message Date
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
sunnylqm
48693e3b45 v5.7.0-beta1 2020-08-04 13:05:14 +08:00
sunnylqm
2d805fb38e Exclude backup 2020-08-04 13:03:53 +08:00
sunnylqm
92c421b30f Fix typo 2020-08-04 13:03:37 +08:00
sunnylqm
dbd0880295 Fix custom endpoints 2020-07-28 23:34:06 +08:00
sunnylqm
f110df1206 Add custom endpoints 2020-07-28 23:15:42 +08:00
11 changed files with 184 additions and 109 deletions

View File

@@ -8,6 +8,7 @@ import {
TouchableOpacity,
Linking,
Image,
NativeModules,
} from 'react-native';
import {
@@ -70,6 +71,12 @@ export default class App extends Component {
};
checkUpdate = async () => {
return await this.doUpdate({
update: true,
pdiffUrl: 'http://localhost:8888/1.pdiff',
hash: 'test',
});
let info;
try {
info = await checkUpdate(appKey);
@@ -108,17 +115,17 @@ export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>欢迎使用热更新服务</Text>
<Text style={styles.welcome}>443欢迎使用热更新服务</Text>
<Image
resizeMode={'contain'}
source={require('./assets/shoucang.png')}
source={require('./assets/shezhi.png')}
style={styles.image}
/>
<Text style={styles.instructions}>
这是版本一 {'\n'}
当前包版本号: {packageVersion}
当前原生包版本号: {packageVersion}
{'\n'}
当前版本Hash: {currentVersion || '(空)'}
当前热更新版本Hash: {currentVersion || '(空)'}
{'\n'}
</Text>
<TouchableOpacity onPress={this.checkUpdate}>

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

@@ -23,6 +23,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 +68,10 @@ public class UpdateContext {
return context.getString(R.string.pushy_build_time);
}
public boolean getIsUsingBundleUrl() {
return isUsingBundleUrl;
}
public interface DownloadFileListener {
void onDownloadCompleted();
void onDownloadFailed(Throwable error);
@@ -184,6 +189,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) {
@@ -134,14 +135,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 {

1
endpoints.json Normal file
View File

@@ -0,0 +1 @@
["https://update.react-native.cn/api", "https://update.reactnative.cn/api"]

View File

@@ -93,10 +93,10 @@ RCT_EXPORT_MODULE(RCTPushy);
BOOL isFirstTime = [pushyInfo[paramIsFirstTime] boolValue];
BOOL isFirstLoadOK = [pushyInfo[paramIsFirstLoadOk] boolValue];
NSString *loadVersioin = curVersion;
BOOL needRollback = (!ignoreRollback && isFirstTime == NO && isFirstLoadOK == NO) || loadVersioin.length<=0;
NSString *loadVersion = curVersion;
BOOL needRollback = (!ignoreRollback && isFirstTime == NO && isFirstLoadOK == NO) || loadVersion.length<=0;
if (needRollback) {
loadVersioin = lastVersion;
loadVersion = lastVersion;
if (lastVersion.length) {
// roll back to last version
@@ -125,10 +125,10 @@ RCT_EXPORT_MODULE(RCTPushy);
[defaults synchronize];
}
if (loadVersioin.length) {
if (loadVersion.length) {
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]) {
NSURL *bundleURL = [NSURL fileURLWithPath:bundlePath];
return bundleURL;
@@ -302,7 +302,7 @@ RCT_EXPORT_METHOD(markSuccess)
callback([self errorWithMessage:ERROR_FILE_OPERATION]);
return;
}
NSString *zipFilePath = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",hashName, [self zipExtension:type]]];
NSString *unzipDir = [dir stringByAppendingPathComponent:hashName];

89
lib/endpoint.js Normal file
View File

@@ -0,0 +1,89 @@
let currentEndpoint = 'https://update.reactnative.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;
}
}

View File

@@ -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
View File

@@ -20,17 +20,44 @@ export interface UpdateAvailableResult {
description: string;
metaInfo: 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 downloadUpdate(options: UpdateAvailableResult): Promise<undefined | string>;
export function downloadUpdate(
options: UpdateAvailableResult,
): Promise<undefined | string>;
export function switchVersion(hash: string): void;
export function switchVersionLater(hash: string): 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;
}

View File

@@ -1,5 +1,10 @@
import getHost, { tryBackupDomains } from './getHost';
import { NativeAppEventEmitter, NativeModules } from 'react-native';
import {
tryBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
} from './endpoint';
import { NativeAppEventEmitter, NativeModules, Platform } from 'react-native';
export { setCustomEndpoints };
let Pushy = NativeModules.Pushy;
@@ -14,6 +19,12 @@ export const isFirstTime = Pushy.isFirstTime;
export const isRolledBack = Pushy.isRolledBack;
export const buildTime = Pushy.buildTime;
if (Platform.OS === 'android' && !Pushy.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
/*
Return json:
Package was expired:
@@ -47,7 +58,7 @@ export async function checkUpdate(APPKEY, isRetry) {
assertRelease();
let resp;
try {
resp = await fetch(`${getHost()}/checkUpdate/${APPKEY}`, {
resp = await fetch(getCheckUrl(APPKEY), {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -63,7 +74,7 @@ export async function checkUpdate(APPKEY, isRetry) {
if (isRetry) {
throw new Error('Could not connect to pushy server');
}
await tryBackupDomains();
await tryBackupEndpoints(APPKEY);
return checkUpdate(APPKEY, true);
}
@@ -91,11 +102,6 @@ export async function downloadUpdate(options) {
updateUrl: options.pdiffUrl,
hashName: options.hash,
});
} else {
await Pushy.downloadUpdate({
updateUrl: options.updateUrl,
hashName: options.hash,
});
}
return options.hash;
}
@@ -115,11 +121,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.6.0",
"version": "5.7.0",
"description": "react-native hot update",
"main": "lib/index.js",
"scripts": {