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

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
10ac7073a8 v8.4.0 2023-10-28 18:30:28 +08:00
9 changed files with 52 additions and 158 deletions

1
.gitignore vendored
View File

@@ -44,4 +44,3 @@ npm-debug.log
Example/**/update.json Example/**/update.json
yarn-error.log yarn-error.log
Example/testHotUpdate/.pushy Example/testHotUpdate/.pushy
dist/

View File

@@ -1,21 +1,13 @@
import { logger, promiseAny } from './utils'; import { logger } from './utils';
let currentEndpoint = 'https://update.react-native.cn/api'; let currentEndpoint = 'https://update.react-native.cn/api';
let backupEndpoints: string[] = [ let backupEndpoints: string[] = ['https://update.reactnative.cn/api'];
'https://pushy-koa-qgbgqmcpis.cn-beijing.fcapp.run', let backupEndpointsQueryUrl: string | null = null;
'https://update.reactnative.cn/api',
];
let backupEndpointsQueryUrls = [
'https://gitee.com/sunnylqm/react-native-pushy/raw/master/endpoints.json',
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json',
];
export async function updateBackupEndpoints() { export async function updateBackupEndpoints() {
if (backupEndpointsQueryUrls) { if (backupEndpointsQueryUrl) {
try { try {
const resp = await promiseAny( const resp = await fetch(backupEndpointsQueryUrl);
backupEndpointsQueryUrls.map((queryUrl) => fetch(queryUrl)),
);
const remoteEndpoints = await resp.json(); const remoteEndpoints = await resp.json();
if (Array.isArray(remoteEndpoints)) { if (Array.isArray(remoteEndpoints)) {
backupEndpoints = Array.from( backupEndpoints = Array.from(
@@ -24,7 +16,7 @@ export async function updateBackupEndpoints() {
logger('fetch remote endpoints:', remoteEndpoints); logger('fetch remote endpoints:', remoteEndpoints);
logger('merged backup endpoints:', backupEndpoints); logger('merged backup endpoints:', backupEndpoints);
} }
} catch (e: any) { } catch (e) {
logger('fetch remote endpoints failed'); logger('fetch remote endpoints failed');
} }
} }
@@ -44,17 +36,18 @@ export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
export function setCustomEndpoints({ export function setCustomEndpoints({
main, main,
backups, backups,
backupQueryUrls, backupQueryUrl,
}: { }: {
main: string; main: string;
backups?: string[]; backups?: string[];
backupQueryUrls?: string[]; backupQueryUrl?: string;
}) { }) {
currentEndpoint = main; currentEndpoint = main;
backupEndpointsQueryUrl = null;
if (Array.isArray(backups) && backups.length > 0) { if (Array.isArray(backups) && backups.length > 0) {
backupEndpoints = backups; backupEndpoints = backups;
} }
if (Array.isArray(backupQueryUrls) && backupQueryUrls.length > 0) { if (typeof backupQueryUrl === 'string') {
backupEndpointsQueryUrls = backupQueryUrls; backupEndpointsQueryUrl = backupQueryUrl;
} }
} }

View File

@@ -15,4 +15,4 @@ export const downloadAndInstallApk = noop;
export const setCustomEndpoints = noop; export const setCustomEndpoints = noop;
export const getCurrentVersionInfo = noop; export const getCurrentVersionInfo = noop;
export const simpleUpdate = (app) => app; export const simpleUpdate = (app) => app;
export const onPushyEvents = noop; export const onEvents = noop;

View File

@@ -16,7 +16,7 @@ import {
UpdateAvailableResult, UpdateAvailableResult,
UpdateEventsListener, UpdateEventsListener,
} from './type'; } from './type';
import { assertRelease, logger, promiseAny, testUrls } from './utils'; import { assertRelease, logger } from './utils';
export { setCustomEndpoints }; export { setCustomEndpoints };
const { const {
version: v, version: v,
@@ -73,7 +73,7 @@ if (!uuid) {
const noop = () => {}; const noop = () => {};
let reporter: UpdateEventsListener = noop; let reporter: UpdateEventsListener = noop;
export function onPushyEvents(customReporter: UpdateEventsListener) { export function onEvents(customReporter: UpdateEventsListener) {
reporter = customReporter; reporter = customReporter;
if (isRolledBack) { if (isRolledBack) {
report({ report({
@@ -154,7 +154,7 @@ export async function checkUpdate(APPKEY: string) {
let resp; let resp;
try { try {
resp = await fetch(getCheckUrl(APPKEY), fetchPayload); resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
} catch (e: any) { } catch (e) {
report({ report({
type: 'errorChecking', type: 'errorChecking',
message: '无法连接主更新服务器,尝试备用节点', message: '无法连接主更新服务器,尝试备用节点',
@@ -162,7 +162,7 @@ export async function checkUpdate(APPKEY: string) {
const backupEndpoints = await updateBackupEndpoints(); const backupEndpoints = await updateBackupEndpoints();
if (backupEndpoints) { if (backupEndpoints) {
try { try {
resp = await promiseAny( resp = await Promise.race(
backupEndpoints.map((endpoint) => backupEndpoints.map((endpoint) =>
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload), fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
), ),
@@ -255,48 +255,41 @@ export async function downloadUpdate(
} }
let succeeded = false; let succeeded = false;
report({ type: 'downloading' }); report({ type: 'downloading' });
const diffUrl = (await testUrls(options.diffUrls)) || options.diffUrl; if (options.diffUrl) {
if (diffUrl) {
logger('downloading diff'); logger('downloading diff');
try { try {
await PushyModule.downloadPatchFromPpk({ await PushyModule.downloadPatchFromPpk({
updateUrl: diffUrl, updateUrl: options.diffUrl,
hash: options.hash, hash: options.hash,
originHash: currentVersion, originHash: currentVersion,
}); });
succeeded = true; succeeded = true;
} catch (e: any) { } catch (e) {
logger(`diff error: ${e.message}, try pdiff`); logger(`diff error: ${e.message}, try pdiff`);
} }
} }
if (!succeeded) { if (!succeeded && options.pdiffUrl) {
const pdiffUrl = (await testUrls(options.pdiffUrls)) || options.pdiffUrl; logger('downloading pdiff');
if (pdiffUrl) { try {
logger('downloading pdiff'); await PushyModule.downloadPatchFromPackage({
try { updateUrl: options.pdiffUrl,
await PushyModule.downloadPatchFromPackage({ hash: options.hash,
updateUrl: pdiffUrl, });
hash: options.hash, succeeded = true;
}); } catch (e) {
succeeded = true; logger(`pdiff error: ${e.message}, try full patch`);
} catch (e: any) {
logger(`pdiff error: ${e.message}, try full patch`);
}
} }
} }
if (!succeeded) { if (!succeeded && options.updateUrl) {
const updateUrl = (await testUrls(options.updateUrls)) || options.updateUrl; logger('downloading full patch');
if (updateUrl) { try {
logger('downloading full patch'); await PushyModule.downloadFullUpdate({
try { updateUrl: options.updateUrl,
await PushyModule.downloadFullUpdate({ hash: options.hash,
updateUrl: updateUrl, });
hash: options.hash, succeeded = true;
}); } catch (e) {
succeeded = true; logger(`full patch error: ${e.message}`);
} catch (e: any) {
logger(`full patch error: ${e.message}`);
}
} }
} }
progressHandler && progressHandler.remove(); progressHandler && progressHandler.remove();
@@ -371,7 +364,7 @@ export async function downloadAndInstallApk({
if (granted !== PermissionsAndroid.RESULTS.GRANTED) { if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return report({ type: 'rejectStoragePermission' }); return report({ type: 'rejectStoragePermission' });
} }
} catch (err: any) { } catch (err) {
return report({ type: 'errorStoragePermission' }); return report({ type: 'errorStoragePermission' });
} }
} }

View File

@@ -16,25 +16,25 @@ import {
switchVersionLater, switchVersionLater,
markSuccess, markSuccess,
downloadAndInstallApk, downloadAndInstallApk,
onPushyEvents, onEvents,
} from './main'; } from './main';
import { UpdateEventsListener } from './type'; import { UpdateEventsListener } from './type';
export function simpleUpdate( export function simpleUpdate(
WrappedComponent: ComponentType, WrappedComponent: ComponentType,
options: { appKey?: string; onPushyEvents?: UpdateEventsListener } = {}, options: { appKey?: string; onEvents?: UpdateEventsListener } = {},
) { ) {
const { appKey, onPushyEvents: eventListeners } = options; const { appKey, onEvents: eventListeners } = options;
if (!appKey) { if (!appKey) {
throw new Error('appKey is required for simpleUpdate()'); throw new Error('appKey is required for simpleUpdate()');
} }
if (typeof eventListeners === 'function') { if (typeof eventListeners === 'function') {
onPushyEvents(eventListeners); onEvents(eventListeners);
} }
return __DEV__ return __DEV__
? WrappedComponent ? WrappedComponent
: class AppUpdate extends PureComponent { : class AppUpdate extends PureComponent {
stateListener: NativeEventSubscription | null = null; stateListener: NativeEventSubscription;
componentDidMount() { componentDidMount() {
if (isRolledBack) { if (isRolledBack) {
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本'); Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
@@ -77,7 +77,7 @@ export function simpleUpdate(
}, },
}, },
]); ]);
} catch (err: any) { } catch (err) {
Alert.alert('更新失败', err.message); Alert.alert('更新失败', err.message);
} }
}; };
@@ -86,7 +86,7 @@ export function simpleUpdate(
let info; let info;
try { try {
info = await checkUpdate(appKey!); info = await checkUpdate(appKey!);
} catch (err: any) { } catch (err) {
Alert.alert('更新检查失败', err.message); Alert.alert('更新检查失败', err.message);
return; return;
} }

View File

@@ -19,11 +19,8 @@ export interface UpdateAvailableResult {
description: string; description: string;
metaInfo: string; metaInfo: string;
pdiffUrl: string; pdiffUrl: string;
pdiffUrls?: string[];
diffUrl?: string; diffUrl?: string;
diffUrls?: string[];
updateUrl?: string; updateUrl?: string;
updateUrls?: string[];
} }
export type CheckResult = export type CheckResult =

View File

@@ -1,22 +1,3 @@
import { Platform } from 'react-native';
export function promiseAny<T>(promises: Promise<T>[]) {
return new Promise<T>((resolve, reject) => {
let count = 0;
promises.forEach((promise) => {
Promise.resolve(promise)
.then(resolve)
.catch(() => {
count++;
if (count === promises.length) {
reject(new Error('All promises were rejected'));
}
});
});
});
}
export function logger(...args: any[]) { export function logger(...args: any[]) {
console.log('Pushy: ', ...args); console.log('Pushy: ', ...args);
} }
@@ -26,50 +7,3 @@ export function assertRelease() {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.'); throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
} }
} }
const ping =
Platform.OS === 'web'
? Promise.resolve
: async (url: string) => {
let pingFinished = false;
return Promise.race([
fetch(url, {
method: 'HEAD',
})
.then(({ status, statusText }) => {
pingFinished = true;
if (status === 200) {
return url;
}
logger('ping failed', url, status, statusText);
throw new Error('Ping failed');
})
.catch((e) => {
pingFinished = true;
logger('ping error', url, e);
throw e;
}),
new Promise((_, reject) =>
setTimeout(() => {
reject(new Error('Ping timeout'));
if (!pingFinished) {
logger('ping timeout', url);
}
}, 2000),
),
]);
};
export const testUrls = async (urls?: string[]) => {
if (!urls?.length) {
return null;
}
try {
const ret = await promiseAny(urls.map(ping));
if (ret) {
return ret;
}
} catch {}
logger('all ping failed, use first url:', urls[0]);
return urls[0];
};

View File

@@ -1,13 +1,10 @@
{ {
"name": "react-native-update", "name": "react-native-update",
"version": "8.5.6", "version": "8.4.0",
"description": "react-native hot update", "description": "react-native hot update",
"main": "dist/index.js", "main": "lib/index.ts",
"types": "dist/index.d.ts",
"scripts": { "scripts": {
"prepublishOnly": "yarn submodule && yarn build", "prepublish": "yarn submodule",
"build": "yarn clean && tsc",
"clean": "rm -rf dist",
"submodule": "git submodule update --init --recursive", "submodule": "git submodule update --init --recursive",
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"build-lib": "yarn submodule && $ANDROID_HOME/ndk/20.1.5948944/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib" "build-lib": "yarn submodule && $ANDROID_HOME/ndk/20.1.5948944/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib"
@@ -28,7 +25,7 @@
"url": "https://github.com/reactnativecn/react-native-pushy/issues" "url": "https://github.com/reactnativecn/react-native-pushy/issues"
}, },
"peerDependencies": { "peerDependencies": {
"react-native": "*" "react-native": ">=0.57.0"
}, },
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme", "homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
"dependencies": { "dependencies": {
@@ -39,6 +36,5 @@
"@types/react": "^18.2.33", "@types/react": "^18.2.33",
"react-native": "^0.72.6", "react-native": "^0.72.6",
"typescript": "^5.2.2" "typescript": "^5.2.2"
}, }
"packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72"
} }

View File

@@ -1,18 +0,0 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react-native",
"lib": ["es2016", "dom"],
"moduleResolution": "node"
},
"include": ["lib/**/*"],
"exclude": ["node_modules", "dist", "Example"]
}