1
0
mirror of https://gitcode.com/gh_mirrors/re/react-native-pushy.git synced 2025-09-16 11:31:37 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee
This commit is contained in:
sunnylqm
2023-10-28 17:23:03 +08:00
parent 9240c3db23
commit e192964185
11 changed files with 4101 additions and 276 deletions

View File

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

@@ -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;

View File

@@ -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 onEvents = noop;

View File

@@ -1,8 +1,7 @@
import {
tryBackupEndpoints,
updateBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
getReportUrl,
} from './endpoint';
import {
NativeEventEmitter,
@@ -10,62 +9,71 @@ import {
Platform,
PermissionsAndroid,
} from 'react-native';
import {
CheckResult,
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
import { assertRelease, logger } from './utils';
export { setCustomEndpoints };
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
let Pushy = NativeModules.Pushy;
export const PushyModule = NativeModules.Pushy;
if (!Pushy) {
if (!PushyModule) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
}
const PushyConstants = PushyModule;
export const downloadRootDir = Pushy.downloadRootDir;
export const packageVersion = Pushy.packageVersion;
export const currentVersion = Pushy.currentVersion;
export const isFirstTime = Pushy.isFirstTime;
const rolledBackVersion = Pushy.rolledBackVersion;
export const downloadRootDir = PushyConstants.downloadRootDir;
export const packageVersion = PushyConstants.packageVersion;
export const currentVersion = PushyConstants.currentVersion;
export const isFirstTime = PushyConstants.isFirstTime;
const rolledBackVersion = PushyConstants.rolledBackVersion;
export const isRolledBack = typeof rolledBackVersion === 'string';
export const buildTime = Pushy.buildTime;
let blockUpdate = Pushy.blockUpdate;
let uuid = Pushy.uuid;
export const buildTime = PushyConstants.buildTime;
let blockUpdate = PushyConstants.blockUpdate;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !Pushy.isUsingBundleUrl) {
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
function setLocalHashInfo(hash, info) {
Pushy.setLocalHashInfo(hash, JSON.stringify(info));
function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash) {
return JSON.parse(await Pushy.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)) || {} : {};
}
const eventEmitter = new NativeEventEmitter(Pushy);
const eventEmitter = new NativeEventEmitter(PushyModule);
if (!uuid) {
uuid = require('nanoid/non-secure').nanoid();
Pushy.setUuid(uuid);
}
function logger(...args) {
console.log('Pushy: ', ...args);
PushyModule.setUuid(uuid);
}
const noop = () => {};
let reporter = noop;
let reporter: UpdateEventsListener = noop;
export function onEvents(customReporter) {
export function onEvents(customReporter: UpdateEventsListener) {
reporter = customReporter;
if (isRolledBack) {
report({
@@ -77,7 +85,15 @@ export function onEvents(customReporter) {
}
}
function report({ type, message = '', data = {} }) {
function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
logger(type + ' ' + message);
reporter({
type,
@@ -101,19 +117,10 @@ export const cInfo = {
uuid,
};
function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
let lastChecking;
const empty = {};
let lastResult;
export async function checkUpdate(APPKEY, isRetry) {
if (typeof APPKEY !== 'string') {
throw new Error('未检查到合法的APPKEY请查看update.json文件是否正确生成');
}
let lastResult: CheckResult;
export async function checkUpdate(APPKEY: string) {
assertRelease();
const now = Date.now();
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
@@ -131,9 +138,7 @@ export async function checkUpdate(APPKEY, isRetry) {
return lastResult || empty;
}
report({ type: 'checking' });
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), {
const fetchPayload = {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -145,26 +150,43 @@ export async function checkUpdate(APPKEY, isRetry) {
buildTime,
cInfo,
}),
});
};
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
} catch (e) {
if (isRetry) {
report({
type: 'errorChecking',
message: '无法连接主更新服务器,尝试备用节点',
});
const backupEndpoints = await updateBackupEndpoints();
if (backupEndpoints) {
try {
resp = await Promise.race(
backupEndpoints.map((endpoint) =>
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
),
);
} catch {}
}
}
if (!resp) {
report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
return lastResult || empty;
}
await tryBackupEndpoints();
return checkUpdate(APPKEY, true);
}
const result = await resp.json();
lastResult = result;
const result: CheckResult = await resp.json();
lastResult = result;
// @ts-ignore
checkOperation(result.op);
if (resp.status !== 200) {
report({
type: 'errorChecking',
//@ts-ignore
message: result.message,
});
}
@@ -172,7 +194,9 @@ export async function checkUpdate(APPKEY, isRetry) {
return result;
}
function checkOperation(op) {
function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) {
return;
}
@@ -182,14 +206,19 @@ function checkOperation(op) {
reason: action.reason,
until: Math.round((Date.now() + action.duration) / 1000),
};
Pushy.setBlockUpdate(blockUpdate);
PushyModule.setBlockUpdate(blockUpdate);
}
});
}
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;
@@ -229,7 +258,7 @@ export async function downloadUpdate(options, eventListeners) {
if (options.diffUrl) {
logger('downloading diff');
try {
await Pushy.downloadPatchFromPpk({
await PushyModule.downloadPatchFromPpk({
updateUrl: options.diffUrl,
hash: options.hash,
originHash: currentVersion,
@@ -242,7 +271,7 @@ export async function downloadUpdate(options, eventListeners) {
if (!succeeded && options.pdiffUrl) {
logger('downloading pdiff');
try {
await Pushy.downloadPatchFromPackage({
await PushyModule.downloadPatchFromPackage({
updateUrl: options.pdiffUrl,
hash: options.hash,
});
@@ -254,7 +283,7 @@ export async function downloadUpdate(options, eventListeners) {
if (!succeeded && options.updateUrl) {
logger('downloading full patch');
try {
await Pushy.downloadFullUpdate({
await PushyModule.downloadFullUpdate({
updateUrl: options.updateUrl,
hash: options.hash,
});
@@ -276,7 +305,7 @@ export async function downloadUpdate(options, eventListeners) {
return options.hash;
}
function assertHash(hash) {
function assertHash(hash: string) {
if (!downloadedHash) {
logger(`no downloaded hash`);
return;
@@ -288,19 +317,19 @@ function assertHash(hash) {
return true;
}
export function switchVersion(hash) {
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
Pushy.reloadUpdate({ hash });
PushyModule.reloadUpdate({ hash });
}
}
export function switchVersionLater(hash) {
export function switchVersionLater(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
Pushy.setNeedUpdate({ hash });
PushyModule.setNeedUpdate({ hash });
}
}
@@ -312,13 +341,22 @@ export function markSuccess() {
return;
}
marked = true;
Pushy.markSuccess();
report(currentVersion, 'success');
PushyModule.markSuccess();
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,
@@ -335,14 +373,14 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
(progressData: ProgressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
await Pushy.downloadAndInstallApk({
await PushyModule.downloadAndInstallApk({
url,
target: 'update.apk',
hash,

View File

@@ -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,
onEvents,
} from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(WrappedComponent, options = {}) {
const { appKey } = options;
export function simpleUpdate(
WrappedComponent: ComponentType,
options: { appKey?: string; onEvents?: UpdateEventsListener } = {},
) {
const { appKey, onEvents: eventListeners } = options;
if (!appKey) {
throw new Error('appKey is required for simpleUpdate()');
}
if (typeof eventListeners === 'function') {
onEvents(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
View 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
View 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 版本中运行.');
}
}

View File

@@ -2,7 +2,7 @@
"name": "react-native-update",
"version": "8.2.0",
"description": "react-native hot update",
"main": "lib/index.js",
"main": "lib/index.ts",
"scripts": {
"prepublish": "yarn submodule",
"submodule": "git submodule update --init --recursive",
@@ -25,10 +25,16 @@
"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": {
"nanoid": "^3.3.3"
},
"devDependencies": {
"@types/node": "^20.8.9",
"@types/react": "^18.2.33",
"react-native": "^0.72.6",
"typescript": "^5.2.2"
}
}

3819
yarn.lock

File diff suppressed because it is too large Load Diff