mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-18 00:56:10 +08:00
Compare commits
28 Commits
v9.0.0-bet
...
v9.1.4
Author | SHA1 | Date | |
---|---|---|---|
![]() |
b747b1f356 | ||
![]() |
7752581470 | ||
![]() |
33eb89d2a7 | ||
![]() |
d111bf5a9c | ||
![]() |
23346a5f1d | ||
![]() |
5aca2104c2 | ||
![]() |
fe0a05db3d | ||
![]() |
2b287786ff | ||
![]() |
7d128900cd | ||
![]() |
189e3ec78e | ||
![]() |
821722165a | ||
![]() |
6cb53ac655 | ||
![]() |
7b9a24168a | ||
![]() |
c6354bbedc | ||
![]() |
b53878c291 | ||
![]() |
ab01312f8d | ||
![]() |
44784b6d3e | ||
![]() |
30c21fed91 | ||
![]() |
15af7802ad | ||
![]() |
8bed6ef979 | ||
![]() |
7d03dc24b7 | ||
![]() |
18849ee441 | ||
![]() |
3ba1df2020 | ||
![]() |
7152ef7304 | ||
![]() |
094eb3f267 | ||
![]() |
6d01ce5152 | ||
![]() |
8bf1fed3f8 | ||
![]() |
39c4a6d339 |
@@ -1,5 +1,5 @@
|
||||
#import "AppDelegate.h"
|
||||
|
||||
#import "RCTPushy.h"
|
||||
#import <React/RCTBridge.h>
|
||||
#import <React/RCTBundleURLProvider.h>
|
||||
#import <React/RCTRootView.h>
|
||||
@@ -87,7 +87,7 @@ static NSString *const kRNConcurrentRoot = @"concurrentRoot";
|
||||
#if DEBUG
|
||||
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
|
||||
#else
|
||||
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
|
||||
return [RCTPushy bundleURL];
|
||||
#endif
|
||||
}
|
||||
|
||||
|
@@ -24,6 +24,19 @@
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
<key>NSExceptionDomains</key>
|
||||
<dict>
|
||||
<key>localhost</key>
|
||||
<dict>
|
||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>NSLocationWhenInUseUsageDescription</key>
|
||||
<string></string>
|
||||
<key>UILaunchStoryboardName</key>
|
||||
@@ -40,18 +53,5 @@
|
||||
</array>
|
||||
<key>UIViewControllerBasedStatusBarAppearance</key>
|
||||
<false/>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
<dict>
|
||||
<key>NSAllowsArbitraryLoads</key>
|
||||
<true/>
|
||||
<key>NSExceptionDomains</key>
|
||||
<dict>
|
||||
<key>localhost</key>
|
||||
<dict>
|
||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
|
@@ -10,7 +10,7 @@
|
||||
|
||||
1. 基于阿里云高速 CDN 分发,对比其他服务器在国外的热更新服务,分发更稳定,更新成功率极高。
|
||||
2. 基于 bsdiff/hdiff 算法创建的**超小更新包**,通常版本迭代后在几十 KB 级别(其他全量热更新服务所需流量通常在几十 MB 级别)。
|
||||
3. 始终跟进 RN 最新正式版本,第一时间提供支持。支持 hermes 字节码格式。(暂不支持新架构,会待其相对稳定后跟进)
|
||||
3. 始终跟进 RN 最新正式版本,第一时间提供支持。支持 hermes 字节码格式。支持新架构。
|
||||
4. 跨越多个版本进行更新时,只需要下载**一个更新包**,不需要逐版本依次更新。
|
||||
5. 命令行工具 & 网页双端管理,版本发布过程简单便捷,完全可以集成 CI。
|
||||
6. 支持崩溃回滚,安全可靠。
|
||||
|
1
android/proguard.pro
vendored
1
android/proguard.pro
vendored
@@ -1,2 +1,3 @@
|
||||
-keepnames class cn.reactnative.modules.update.DownloadTask { *; }
|
||||
-keepnames class cn.reactnative.modules.update.UpdateModuleImpl { *; }
|
||||
-keepnames class com.facebook.react.ReactInstanceManager { *; }
|
@@ -1,9 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="cn.reactnative.modules.update">
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<application>
|
||||
<meta-data android:name="pushy_build_time" android:value="@string/pushy_build_time" />
|
||||
<provider
|
||||
|
@@ -1,51 +1,45 @@
|
||||
/**
|
||||
* @format
|
||||
* @flow strict-local
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
|
||||
import { TurboModuleRegistry } from 'react-native';
|
||||
|
||||
export interface Spec extends TurboModule {
|
||||
getConstants: () => {
|
||||
downloadRootDir: string,
|
||||
packageVersion: string,
|
||||
currentVersion: string,
|
||||
isFirstTime: boolean,
|
||||
rolledBackVersion: string,
|
||||
buildTime: string,
|
||||
blockUpdate: Object,
|
||||
uuid: string,
|
||||
isUsingBundleUrl: boolean,
|
||||
downloadRootDir: string;
|
||||
packageVersion: string;
|
||||
currentVersion: string;
|
||||
isFirstTime: boolean;
|
||||
rolledBackVersion: string;
|
||||
buildTime: string;
|
||||
blockUpdate: Object;
|
||||
uuid: string;
|
||||
isUsingBundleUrl: boolean;
|
||||
};
|
||||
setLocalHashInfo(hash: string, info: string): Promise<void>;
|
||||
getLocalHashInfo(hash: string): Promise<string>;
|
||||
setUuid(uuid: string): Promise<void>;
|
||||
setBlockUpdate(options: { reason: string, until: number }): Promise<void>;
|
||||
setBlockUpdate(options: { reason: string; until: number }): Promise<void>;
|
||||
reloadUpdate(options: { hash: string }): Promise<void>;
|
||||
setNeedUpdate(options: { hash: string }): Promise<void>;
|
||||
markSuccess(): Promise<void>;
|
||||
downloadPatchFromPpk(options: {
|
||||
updateUrl: string,
|
||||
hash: string,
|
||||
originHash: string,
|
||||
updateUrl: string;
|
||||
hash: string;
|
||||
originHash: string;
|
||||
}): Promise<void>;
|
||||
downloadPatchFromPackage(options: {
|
||||
updateUrl: string,
|
||||
hash: string,
|
||||
updateUrl: string;
|
||||
hash: string;
|
||||
}): Promise<void>;
|
||||
downloadFullUpdate(options: {
|
||||
updateUrl: string,
|
||||
hash: string,
|
||||
updateUrl: string;
|
||||
hash: string;
|
||||
}): Promise<void>;
|
||||
downloadAndInstallApk(options: {
|
||||
url: string,
|
||||
target: string,
|
||||
hash: string,
|
||||
url: string;
|
||||
target: string;
|
||||
hash: string;
|
||||
}): Promise<void>;
|
||||
addListener(eventName: string): void;
|
||||
removeListeners(count: number): void;
|
||||
}
|
||||
|
||||
export default (TurboModuleRegistry.get<Spec>('Pushy'): ?Spec);
|
||||
export default TurboModuleRegistry.get<Spec>('Pushy') as Spec | null;
|
@@ -1,93 +0,0 @@
|
||||
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 getReportUrl(endpoint = currentEndpoint) {
|
||||
return `${endpoint}/report`;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
53
lib/endpoint.ts
Normal file
53
lib/endpoint.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { logger } from './utils';
|
||||
|
||||
let currentEndpoint = 'https://update.react-native.cn/api';
|
||||
let backupEndpoints: string[] = ['https://update.reactnative.cn/api'];
|
||||
let backupEndpointsQueryUrl: string | null = null;
|
||||
|
||||
export async function updateBackupEndpoints() {
|
||||
if (backupEndpointsQueryUrl) {
|
||||
try {
|
||||
const resp = await fetch(backupEndpointsQueryUrl);
|
||||
const remoteEndpoints = await resp.json();
|
||||
if (Array.isArray(remoteEndpoints)) {
|
||||
backupEndpoints = Array.from(
|
||||
new Set([...backupEndpoints, ...remoteEndpoints]),
|
||||
);
|
||||
logger('fetch remote endpoints:', remoteEndpoints);
|
||||
logger('merged backup endpoints:', backupEndpoints);
|
||||
}
|
||||
} catch (e) {
|
||||
logger('fetch remote endpoints failed');
|
||||
}
|
||||
}
|
||||
return backupEndpoints;
|
||||
}
|
||||
|
||||
export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
|
||||
return `${endpoint}/checkUpdate/${APPKEY}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}) {
|
||||
currentEndpoint = main;
|
||||
backupEndpointsQueryUrl = null;
|
||||
if (Array.isArray(backups) && backups.length > 0) {
|
||||
backupEndpoints = backups;
|
||||
}
|
||||
if (typeof backupQueryUrl === 'string') {
|
||||
backupEndpointsQueryUrl = backupQueryUrl;
|
||||
}
|
||||
}
|
94
lib/index.d.ts
vendored
94
lib/index.d.ts
vendored
@@ -1,94 +0,0 @@
|
||||
export const downloadRootDir: string;
|
||||
export const packageVersion: string;
|
||||
export const currentVersion: string;
|
||||
export const isFirstTime: boolean;
|
||||
export const isRolledBack: boolean;
|
||||
|
||||
export interface ExpiredResult {
|
||||
upToDate?: false;
|
||||
expired: true;
|
||||
downloadUrl: string;
|
||||
}
|
||||
|
||||
export interface UpTodateResult {
|
||||
expired?: false;
|
||||
upToDate: true;
|
||||
paused?: 'app' | 'package';
|
||||
}
|
||||
|
||||
export interface UpdateAvailableResult {
|
||||
expired?: false;
|
||||
upToDate?: false;
|
||||
update: true;
|
||||
name: string; // version name
|
||||
hash: string;
|
||||
description: string;
|
||||
metaInfo: string;
|
||||
pdiffUrl: string;
|
||||
diffUrl?: string;
|
||||
}
|
||||
|
||||
export type CheckResult =
|
||||
| ExpiredResult
|
||||
| UpTodateResult
|
||||
| UpdateAvailableResult;
|
||||
|
||||
export function checkUpdate(appkey: string): Promise<CheckResult>;
|
||||
|
||||
export function downloadUpdate(
|
||||
info: UpdateAvailableResult,
|
||||
eventListeners?: {
|
||||
onDownloadProgress?: (data: ProgressData) => void;
|
||||
},
|
||||
): Promise<undefined | string>;
|
||||
|
||||
export function switchVersion(hash: string): void;
|
||||
|
||||
export function switchVersionLater(hash: string): void;
|
||||
|
||||
export function markSuccess(): void;
|
||||
|
||||
export function downloadAndInstallApk({
|
||||
url,
|
||||
onDownloadProgress,
|
||||
}: {
|
||||
url: string;
|
||||
onDownloadProgress?: (data: ProgressData) => void;
|
||||
}): Promise<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;
|
||||
|
||||
export function getCurrentVersionInfo(): Promise<{
|
||||
name?: string;
|
||||
description?: string;
|
||||
metaInfo?: string;
|
||||
}>;
|
||||
|
||||
interface ProgressData {
|
||||
hash: string;
|
||||
received: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface SimpleUpdateOptions {
|
||||
appKey: string;
|
||||
}
|
||||
|
||||
export function simpleUpdate(
|
||||
wrappedComponent: any,
|
||||
options: SimpleUpdateOptions,
|
||||
): any;
|
@@ -14,4 +14,5 @@ export const markSuccess = noop;
|
||||
export const downloadAndInstallApk = noop;
|
||||
export const setCustomEndpoints = noop;
|
||||
export const getCurrentVersionInfo = noop;
|
||||
export const simpleUpdate = noop;
|
||||
export const simpleUpdate = (app) => app;
|
||||
export const onPushyEvents = noop;
|
||||
|
@@ -1,8 +1,7 @@
|
||||
import {
|
||||
tryBackupEndpoints,
|
||||
updateBackupEndpoints,
|
||||
getCheckUrl,
|
||||
setCustomEndpoints,
|
||||
getReportUrl,
|
||||
} from './endpoint';
|
||||
import {
|
||||
NativeEventEmitter,
|
||||
@@ -10,6 +9,14 @@ import {
|
||||
Platform,
|
||||
PermissionsAndroid,
|
||||
} from 'react-native';
|
||||
import {
|
||||
CheckResult,
|
||||
EventType,
|
||||
ProgressData,
|
||||
UpdateAvailableResult,
|
||||
UpdateEventsListener,
|
||||
} from './type';
|
||||
import { assertRelease, logger } from './utils';
|
||||
export { setCustomEndpoints };
|
||||
const {
|
||||
version: v,
|
||||
@@ -45,15 +52,19 @@ if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
|
||||
);
|
||||
}
|
||||
|
||||
function setLocalHashInfo(hash, info) {
|
||||
function setLocalHashInfo(hash: string, info: Record<string, any>) {
|
||||
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
|
||||
}
|
||||
|
||||
async function getLocalHashInfo(hash) {
|
||||
async function getLocalHashInfo(hash: string) {
|
||||
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
|
||||
}
|
||||
|
||||
export async function getCurrentVersionInfo() {
|
||||
export async function getCurrentVersionInfo(): Promise<{
|
||||
name?: string;
|
||||
description?: string;
|
||||
metaInfo?: string;
|
||||
}> {
|
||||
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
|
||||
}
|
||||
|
||||
@@ -64,34 +75,46 @@ if (!uuid) {
|
||||
PushyModule.setUuid(uuid);
|
||||
}
|
||||
|
||||
function logger(text) {
|
||||
console.log(`Pushy: ${text}`);
|
||||
const noop = () => {};
|
||||
let reporter: UpdateEventsListener = noop;
|
||||
|
||||
export function onPushyEvents(customReporter: UpdateEventsListener) {
|
||||
reporter = customReporter;
|
||||
if (isRolledBack) {
|
||||
report({
|
||||
type: 'rollback',
|
||||
data: {
|
||||
rolledBackVersion,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function report(hash, type) {
|
||||
logger(type);
|
||||
fetch(getReportUrl(), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
hash,
|
||||
type,
|
||||
function report({
|
||||
type,
|
||||
message = '',
|
||||
data = {},
|
||||
}: {
|
||||
type: EventType;
|
||||
message?: string;
|
||||
data?: Record<string, string | number>;
|
||||
}) {
|
||||
logger(type + ' ' + message);
|
||||
reporter({
|
||||
type,
|
||||
data: {
|
||||
currentVersion,
|
||||
cInfo,
|
||||
packageVersion,
|
||||
buildTime,
|
||||
}),
|
||||
}).catch((_e) => {});
|
||||
message,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
logger('uuid: ' + uuid);
|
||||
|
||||
if (isRolledBack) {
|
||||
report(rolledBackVersion, 'rollback');
|
||||
}
|
||||
|
||||
export const cInfo = {
|
||||
pushy: require('../package.json').version,
|
||||
rn: RNVersion,
|
||||
@@ -99,67 +122,86 @@ export const cInfo = {
|
||||
uuid,
|
||||
};
|
||||
|
||||
function assertRelease() {
|
||||
if (__DEV__) {
|
||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
||||
}
|
||||
}
|
||||
|
||||
let checkingThrottling = false;
|
||||
export async function checkUpdate(APPKEY, isRetry) {
|
||||
let lastChecking;
|
||||
const empty = {};
|
||||
let lastResult: CheckResult;
|
||||
export async function checkUpdate(APPKEY: string) {
|
||||
assertRelease();
|
||||
if (checkingThrottling) {
|
||||
logger('repeated checking, ignored');
|
||||
return;
|
||||
const now = Date.now();
|
||||
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
|
||||
// logger('repeated checking, ignored');
|
||||
return lastResult;
|
||||
}
|
||||
checkingThrottling = true;
|
||||
setTimeout(() => {
|
||||
checkingThrottling = false;
|
||||
}, 3000);
|
||||
lastChecking = now;
|
||||
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
|
||||
throw new Error(
|
||||
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
|
||||
blockUpdate.until * 1000,
|
||||
).toLocaleString()}"之后重试。`,
|
||||
);
|
||||
});
|
||||
return lastResult || empty;
|
||||
}
|
||||
if (typeof APPKEY !== 'string') {
|
||||
throw new Error('未检查到合法的APPKEY,请查看update.json文件是否正确生成');
|
||||
}
|
||||
logger('checking update');
|
||||
report({ type: 'checking' });
|
||||
const fetchPayload = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
packageVersion,
|
||||
hash: currentVersion,
|
||||
buildTime,
|
||||
cInfo,
|
||||
}),
|
||||
};
|
||||
let resp;
|
||||
try {
|
||||
resp = await fetch(getCheckUrl(APPKEY), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
packageVersion,
|
||||
hash: currentVersion,
|
||||
buildTime,
|
||||
cInfo,
|
||||
}),
|
||||
});
|
||||
resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
|
||||
} catch (e) {
|
||||
if (isRetry) {
|
||||
throw new Error('无法连接更新服务器,请检查网络连接后重试');
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
message: '无法连接主更新服务器,尝试备用节点',
|
||||
});
|
||||
const backupEndpoints = await updateBackupEndpoints();
|
||||
if (backupEndpoints) {
|
||||
try {
|
||||
resp = await Promise.race(
|
||||
backupEndpoints.map((endpoint) =>
|
||||
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
|
||||
),
|
||||
);
|
||||
} catch {}
|
||||
}
|
||||
await tryBackupEndpoints();
|
||||
return checkUpdate(APPKEY, true);
|
||||
}
|
||||
const result = await resp.json();
|
||||
if (!resp) {
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
message: '无法连接更新服务器,请检查网络连接后重试',
|
||||
});
|
||||
return lastResult || empty;
|
||||
}
|
||||
const result: CheckResult = await resp.json();
|
||||
|
||||
lastResult = result;
|
||||
// @ts-ignore
|
||||
checkOperation(result.op);
|
||||
|
||||
if (resp.status !== 200) {
|
||||
throw new Error(result.message);
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
//@ts-ignore
|
||||
message: result.message,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function checkOperation(op) {
|
||||
function checkOperation(
|
||||
op: { type: string; reason: string; duration: number }[],
|
||||
) {
|
||||
if (!Array.isArray(op)) {
|
||||
return;
|
||||
}
|
||||
@@ -175,8 +217,13 @@ function checkOperation(op) {
|
||||
}
|
||||
|
||||
let downloadingThrottling = false;
|
||||
let downloadedHash;
|
||||
export async function downloadUpdate(options, eventListeners) {
|
||||
let downloadedHash: string;
|
||||
export async function downloadUpdate(
|
||||
options: UpdateAvailableResult,
|
||||
eventListeners?: {
|
||||
onDownloadProgress?: (data: ProgressData) => void;
|
||||
},
|
||||
) {
|
||||
assertRelease();
|
||||
if (!options.update) {
|
||||
return;
|
||||
@@ -212,6 +259,7 @@ export async function downloadUpdate(options, eventListeners) {
|
||||
}
|
||||
}
|
||||
let succeeded = false;
|
||||
report({ type: 'downloading' });
|
||||
if (options.diffUrl) {
|
||||
logger('downloading diff');
|
||||
try {
|
||||
@@ -251,8 +299,7 @@ export async function downloadUpdate(options, eventListeners) {
|
||||
}
|
||||
progressHandler && progressHandler.remove();
|
||||
if (!succeeded) {
|
||||
report(options.hash, 'error');
|
||||
throw new Error('all update attempts failed');
|
||||
return report({ type: 'errorUpdate', data: { newVersion: options.hash } });
|
||||
}
|
||||
setLocalHashInfo(options.hash, {
|
||||
name: options.name,
|
||||
@@ -263,7 +310,7 @@ export async function downloadUpdate(options, eventListeners) {
|
||||
return options.hash;
|
||||
}
|
||||
|
||||
function assertHash(hash) {
|
||||
function assertHash(hash: string) {
|
||||
if (!downloadedHash) {
|
||||
logger(`no downloaded hash`);
|
||||
return;
|
||||
@@ -275,15 +322,17 @@ function assertHash(hash) {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function switchVersion(hash) {
|
||||
let applyingUpdate = false;
|
||||
export function switchVersion(hash: string) {
|
||||
assertRelease();
|
||||
if (assertHash(hash)) {
|
||||
if (assertHash(hash) && !applyingUpdate) {
|
||||
logger('switchVersion: ' + hash);
|
||||
applyingUpdate = true;
|
||||
PushyModule.reloadUpdate({ hash });
|
||||
}
|
||||
}
|
||||
|
||||
export function switchVersionLater(hash) {
|
||||
export function switchVersionLater(hash: string) {
|
||||
assertRelease();
|
||||
if (assertHash(hash)) {
|
||||
logger('switchVersionLater: ' + hash);
|
||||
@@ -300,21 +349,30 @@ export function markSuccess() {
|
||||
}
|
||||
marked = true;
|
||||
PushyModule.markSuccess();
|
||||
report(currentVersion, 'success');
|
||||
report({ type: 'markSuccess' });
|
||||
}
|
||||
|
||||
export async function downloadAndInstallApk({ url, onDownloadProgress }) {
|
||||
logger('downloadAndInstallApk');
|
||||
if (Platform.OS === 'android' && Platform.Version <= 23) {
|
||||
export async function downloadAndInstallApk({
|
||||
url,
|
||||
onDownloadProgress,
|
||||
}: {
|
||||
url: string;
|
||||
onDownloadProgress?: (data: ProgressData) => void;
|
||||
}) {
|
||||
if (Platform.OS !== 'android') {
|
||||
return;
|
||||
}
|
||||
report({ type: 'downloadingApk' });
|
||||
if (Platform.Version <= 23) {
|
||||
try {
|
||||
const granted = await PermissionsAndroid.request(
|
||||
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
|
||||
);
|
||||
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
|
||||
return;
|
||||
return report({ type: 'rejectStoragePermission' });
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(err);
|
||||
return report({ type: 'errorStoragePermission' });
|
||||
}
|
||||
}
|
||||
let hash = Date.now().toString();
|
||||
@@ -322,7 +380,7 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
|
||||
if (onDownloadProgress) {
|
||||
progressHandler = eventEmitter.addListener(
|
||||
'RCTPushyDownloadProgress',
|
||||
(progressData) => {
|
||||
(progressData: ProgressData) => {
|
||||
if (progressData.hash === hash) {
|
||||
onDownloadProgress(progressData);
|
||||
}
|
||||
@@ -333,6 +391,8 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
|
||||
url,
|
||||
target: 'update.apk',
|
||||
hash,
|
||||
}).catch(() => {
|
||||
report({ type: 'errowDownloadAndInstallApk' });
|
||||
});
|
||||
progressHandler && progressHandler.remove();
|
||||
}
|
@@ -1,5 +1,11 @@
|
||||
import React, { Component } from 'react';
|
||||
import { Platform, Alert, Linking, AppState } from 'react-native';
|
||||
import React, { PureComponent, ComponentType } from 'react';
|
||||
import {
|
||||
Platform,
|
||||
Alert,
|
||||
Linking,
|
||||
AppState,
|
||||
NativeEventSubscription,
|
||||
} from 'react-native';
|
||||
|
||||
import {
|
||||
isFirstTime,
|
||||
@@ -10,16 +16,25 @@ import {
|
||||
switchVersionLater,
|
||||
markSuccess,
|
||||
downloadAndInstallApk,
|
||||
onPushyEvents,
|
||||
} from './main';
|
||||
import { UpdateEventsListener } from './type';
|
||||
|
||||
export function simpleUpdate(WrappedComponent, options = {}) {
|
||||
const { appKey } = options;
|
||||
export function simpleUpdate(
|
||||
WrappedComponent: ComponentType,
|
||||
options: { appKey?: string; onPushyEvents?: UpdateEventsListener } = {},
|
||||
) {
|
||||
const { appKey, onPushyEvents: eventListeners } = options;
|
||||
if (!appKey) {
|
||||
throw new Error('appKey is required for simpleUpdate()');
|
||||
}
|
||||
if (typeof eventListeners === 'function') {
|
||||
onPushyEvents(eventListeners);
|
||||
}
|
||||
return __DEV__
|
||||
? WrappedComponent
|
||||
: class AppUpdate extends Component {
|
||||
: class AppUpdate extends PureComponent {
|
||||
stateListener: NativeEventSubscription;
|
||||
componentDidMount() {
|
||||
if (isRolledBack) {
|
||||
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
|
||||
@@ -70,7 +85,7 @@ export function simpleUpdate(WrappedComponent, options = {}) {
|
||||
checkUpdate = async () => {
|
||||
let info;
|
||||
try {
|
||||
info = await checkUpdate(appKey);
|
||||
info = await checkUpdate(appKey!);
|
||||
} catch (err) {
|
||||
Alert.alert('更新检查失败', err.message);
|
||||
return;
|
71
lib/type.ts
Normal file
71
lib/type.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
export interface ExpiredResult {
|
||||
upToDate?: false;
|
||||
expired: true;
|
||||
downloadUrl: string;
|
||||
}
|
||||
|
||||
export interface UpTodateResult {
|
||||
expired?: false;
|
||||
upToDate: true;
|
||||
paused?: 'app' | 'package';
|
||||
}
|
||||
|
||||
export interface UpdateAvailableResult {
|
||||
expired?: false;
|
||||
upToDate?: false;
|
||||
update: true;
|
||||
name: string; // version name
|
||||
hash: string;
|
||||
description: string;
|
||||
metaInfo: string;
|
||||
pdiffUrl: string;
|
||||
diffUrl?: string;
|
||||
updateUrl?: string;
|
||||
}
|
||||
|
||||
export type CheckResult =
|
||||
| ExpiredResult
|
||||
| UpTodateResult
|
||||
| UpdateAvailableResult
|
||||
| {};
|
||||
|
||||
export interface ProgressData {
|
||||
hash: string;
|
||||
received: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export type EventType =
|
||||
| 'rollback'
|
||||
| 'errorChecking'
|
||||
| 'checking'
|
||||
| 'downloading'
|
||||
| 'errorUpdate'
|
||||
| 'markSuccess'
|
||||
| 'downloadingApk'
|
||||
| 'rejectStoragePermission'
|
||||
| 'errorStoragePermission'
|
||||
| 'errowDownloadAndInstallApk';
|
||||
|
||||
export interface EventData {
|
||||
currentVersion: string;
|
||||
cInfo: {
|
||||
pushy: string;
|
||||
rn: string;
|
||||
os: string;
|
||||
uuid: string;
|
||||
};
|
||||
packageVersion: string;
|
||||
buildTime: number;
|
||||
message?: string;
|
||||
rolledBackVersion?: string;
|
||||
newVersion?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
export type UpdateEventsListener = ({
|
||||
type,
|
||||
data,
|
||||
}: {
|
||||
type: EventType;
|
||||
data: EventData;
|
||||
}) => void;
|
9
lib/utils.ts
Normal file
9
lib/utils.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
export function logger(...args: any[]) {
|
||||
console.log('Pushy: ', ...args);
|
||||
}
|
||||
|
||||
export function assertRelease() {
|
||||
if (__DEV__) {
|
||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
||||
}
|
||||
}
|
11
package.json
11
package.json
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "react-native-update",
|
||||
"version": "9.0.0-beta.0",
|
||||
"version": "9.1.4",
|
||||
"description": "react-native hot update",
|
||||
"main": "lib/index.js",
|
||||
"main": "lib/index.ts",
|
||||
"scripts": {
|
||||
"prepublish": "yarn submodule",
|
||||
"submodule": "git submodule update --init --recursive",
|
||||
@@ -39,7 +39,7 @@
|
||||
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react-native": ">=0.27.0"
|
||||
"react-native": ">=0.57.0"
|
||||
},
|
||||
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
||||
"dependencies": {
|
||||
@@ -57,12 +57,15 @@
|
||||
"devDependencies": {
|
||||
"@types/fs-extra": "^9.0.13",
|
||||
"@types/jest": "^29.2.1",
|
||||
"@types/node": "^20.8.9",
|
||||
"@types/react": "^18.2.33",
|
||||
"detox": "^20.5.0",
|
||||
"firebase-tools": "^11.24.1",
|
||||
"fs-extra": "^9.1.0",
|
||||
"jest": "^29.2.1",
|
||||
"pod-install": "^0.1.37",
|
||||
"react-native": "^0.72.6",
|
||||
"ts-jest": "^29.0.3",
|
||||
"typescript": "^4.1.3"
|
||||
"typescript": "^5.2.2"
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +1,7 @@
|
||||
require 'json'
|
||||
|
||||
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
|
||||
folly_version = '2021.06.28.00-v2'
|
||||
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
|
||||
|
||||
Pod::Spec.new do |s|
|
||||
s.name = package['name']
|
||||
s.version = package['version']
|
||||
@@ -41,18 +40,5 @@ Pod::Spec.new do |s|
|
||||
'android/jni/lzma/C/Lzma2Dec.{h,c}']
|
||||
ss.private_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
|
||||
end
|
||||
# This guard prevent to install the dependencies when we run `pod install` in the old architecture.
|
||||
if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
|
||||
s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
|
||||
s.pod_target_xcconfig = {
|
||||
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
|
||||
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
|
||||
}
|
||||
|
||||
s.dependency "React-Codegen"
|
||||
s.dependency "RCT-Folly", folly_version
|
||||
s.dependency "RCTRequired"
|
||||
s.dependency "RCTTypeSafety"
|
||||
s.dependency "ReactCommon/turbomodule/core"
|
||||
end
|
||||
install_modules_dependencies(s)
|
||||
end
|
||||
|
Reference in New Issue
Block a user