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

Compare commits

...

12 Commits

Author SHA1 Message Date
sunnylqm
baebeff7cb v8.5.2 2024-11-13 19:58:12 +08:00
sunnylqm
c7b78f0d46 fix testurl 2024-11-13 19:57:44 +08:00
sunnylqm
21f2c3918e v8.5.1 2024-07-27 21:54:15 +08:00
sunnylqm
c3689e560c v8.5.0 2024-07-27 16:55:00 +08:00
sunnylqm
ab1e62dba5 test cdn urls 2024-07-26 15:37:32 +08:00
sunnylqm
fcfc8c3dbb add testurls 2024-07-26 15:28:13 +08:00
sunnylqm
41af560a39 v8.4.0 2023-10-28 18:30:51 +08:00
sunnylqm
5784f2f046 v8.3.0 2023-10-28 17:23:30 +08:00
sunnylqm
e192964185 feat: ts 2023-10-28 17:23:03 +08:00
sunnylqm
9240c3db23 chore: remove permissions 2023-10-28 17:04:09 +08:00
sunnylqm
427b05f3a4 v8.2.0 2023-09-24 21:12:06 +08:00
sunnylqm
73c3dc538c fix: proguard 2023-09-24 21:11:29 +08:00
14 changed files with 4432 additions and 533 deletions

View File

@@ -1,2 +1,3 @@
-keepnames class cn.reactnative.modules.update.DownloadTask { *; }
-keepnames class cn.reactnative.modules.update.UpdateModule { *; }
-keepnames class com.facebook.react.ReactInstanceManager { *; }

View File

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

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

60
lib/endpoint.ts Normal file
View File

@@ -0,0 +1,60 @@
import { logger, promiseAny } from './utils';
let currentEndpoint = 'https://update.react-native.cn/api';
let backupEndpoints: string[] = [
'https://pushy-koa-qgbgqmcpis.cn-beijing.fcapp.run',
'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() {
if (backupEndpointsQueryUrls) {
try {
const resp = await promiseAny(
backupEndpointsQueryUrls.map((queryUrl) => fetch(queryUrl)),
);
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,
backupQueryUrls,
}: {
main: string;
backups?: string[];
backupQueryUrls?: string[];
}) {
currentEndpoint = main;
if (Array.isArray(backups) && backups.length > 0) {
backupEndpoints = backups;
}
if (Array.isArray(backupQueryUrls) && backupQueryUrls.length > 0) {
backupEndpointsQueryUrls = backupQueryUrls;
}
}

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 onPushyEvents = noop;

View File

@@ -1,332 +0,0 @@
import {
tryBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
getReportUrl,
} from './endpoint';
import {
NativeEventEmitter,
NativeModules,
Platform,
PermissionsAndroid,
} from 'react-native';
export { setCustomEndpoints };
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
let Pushy = NativeModules.Pushy;
if (!Pushy) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
}
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 isRolledBack = typeof rolledBackVersion === 'string';
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的配置',
);
}
function setLocalHashInfo(hash, info) {
Pushy.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash) {
return JSON.parse(await Pushy.getLocalHashInfo(hash));
}
export async function getCurrentVersionInfo() {
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
}
const eventEmitter = new NativeEventEmitter(Pushy);
if (!uuid) {
uuid = require('nanoid/non-secure').nanoid();
Pushy.setUuid(uuid);
}
function logger(text) {
console.log(`Pushy: ${text}`);
}
function report(hash, type) {
logger(type);
fetch(getReportUrl(), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
hash,
type,
cInfo,
packageVersion,
buildTime,
}),
}).catch((_e) => {});
}
logger('uuid: ' + uuid);
if (isRolledBack) {
report(rolledBackVersion, 'rollback');
}
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,
};
function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
let checkingThrottling = false;
export async function checkUpdate(APPKEY, isRetry) {
assertRelease();
if (checkingThrottling) {
logger('repeated checking, ignored');
return;
}
checkingThrottling = true;
setTimeout(() => {
checkingThrottling = false;
}, 3000);
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
throw new Error(
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"之后重试。`,
);
}
if (typeof APPKEY !== 'string') {
throw new Error('未检查到合法的APPKEY请查看update.json文件是否正确生成');
}
logger('checking update');
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,
}),
});
} catch (e) {
if (isRetry) {
throw new Error('无法连接更新服务器,请检查网络连接后重试');
}
await tryBackupEndpoints();
return checkUpdate(APPKEY, true);
}
const result = await resp.json();
checkOperation(result.op);
if (resp.status !== 200) {
throw new Error(result.message);
}
return result;
}
function checkOperation(op) {
if (!Array.isArray(op)) {
return;
}
op.forEach((action) => {
if (action.type === 'block') {
blockUpdate = {
reason: action.reason,
until: Math.round((Date.now() + action.duration) / 1000),
};
Pushy.setBlockUpdate(blockUpdate);
}
});
}
let downloadingThrottling = false;
let downloadedHash;
export async function downloadUpdate(options, eventListeners) {
assertRelease();
if (!options.update) {
return;
}
if (rolledBackVersion === options.hash) {
logger(`rolledback hash ${rolledBackVersion}, ignored`);
return;
}
if (downloadedHash === options.hash) {
logger(`duplicated downloaded hash ${downloadedHash}, ignored`);
return downloadedHash;
}
if (downloadingThrottling) {
logger('repeated downloading, ignored');
return;
}
downloadingThrottling = true;
setTimeout(() => {
downloadingThrottling = false;
}, 3000);
let progressHandler;
if (eventListeners) {
if (eventListeners.onDownloadProgress) {
const downloadCallback = eventListeners.onDownloadProgress;
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
if (progressData.hash === options.hash) {
downloadCallback(progressData);
}
},
);
}
}
let succeeded = false;
if (options.diffUrl) {
logger('downloading diff');
try {
await Pushy.downloadPatchFromPpk({
updateUrl: options.diffUrl,
hash: options.hash,
originHash: currentVersion,
});
succeeded = true;
} catch (e) {
logger(`diff error: ${e.message}, try pdiff`);
}
}
if (!succeeded && options.pdiffUrl) {
logger('downloading pdiff');
try {
await Pushy.downloadPatchFromPackage({
updateUrl: options.pdiffUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`pdiff error: ${e.message}, try full patch`);
}
}
if (!succeeded && options.updateUrl) {
logger('downloading full patch');
try {
await Pushy.downloadFullUpdate({
updateUrl: options.updateUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`full patch error: ${e.message}`);
}
}
progressHandler && progressHandler.remove();
if (!succeeded) {
report(options.hash, 'error');
throw new Error('all update attempts failed');
}
setLocalHashInfo(options.hash, {
name: options.name,
description: options.description,
metaInfo: options.metaInfo,
});
downloadedHash = options.hash;
return options.hash;
}
function assertHash(hash) {
if (!downloadedHash) {
logger(`no downloaded hash`);
return;
}
if (hash !== downloadedHash) {
logger(`use downloaded hash ${downloadedHash} first`);
return;
}
return true;
}
export function switchVersion(hash) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
Pushy.reloadUpdate({ hash });
}
}
export function switchVersionLater(hash) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
Pushy.setNeedUpdate({ hash });
}
}
let marked = false;
export function markSuccess() {
assertRelease();
if (marked) {
logger('repeated markSuccess, ignored');
return;
}
marked = true;
Pushy.markSuccess();
report(currentVersion, 'success');
}
export async function downloadAndInstallApk({ url, onDownloadProgress }) {
logger('downloadAndInstallApk');
if (Platform.OS === 'android' && Platform.Version <= 23) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return;
}
} catch (err) {
console.warn(err);
}
}
let hash = Date.now().toString();
let progressHandler;
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
await Pushy.downloadAndInstallApk({
url,
target: 'update.apk',
hash,
});
progressHandler && progressHandler.remove();
}

398
lib/main.ts Normal file
View File

@@ -0,0 +1,398 @@
import {
updateBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
} from './endpoint';
import {
NativeEventEmitter,
NativeModules,
Platform,
PermissionsAndroid,
} from 'react-native';
import {
CheckResult,
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
import { assertRelease, logger, promiseAny, testUrls } from './utils';
export { setCustomEndpoints };
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
export const PushyModule = NativeModules.Pushy;
if (!PushyModule) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
}
const PushyConstants = PushyModule;
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 = PushyConstants.buildTime;
let blockUpdate = PushyConstants.blockUpdate;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
}
export async function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;
metaInfo?: string;
}> {
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
}
const eventEmitter = new NativeEventEmitter(PushyModule);
if (!uuid) {
uuid = require('nanoid/non-secure').nanoid();
PushyModule.setUuid(uuid);
}
const noop = () => {};
let reporter: UpdateEventsListener = noop;
export function onPushyEvents(customReporter: UpdateEventsListener) {
reporter = customReporter;
if (isRolledBack) {
report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
logger(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
}
logger('uuid: ' + uuid);
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,
};
let lastChecking;
const empty = {};
let lastResult: CheckResult;
export async function checkUpdate(APPKEY: string) {
assertRelease();
const now = Date.now();
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
// logger('repeated checking, ignored');
return lastResult;
}
lastChecking = now;
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
report({
type: 'errorChecking',
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"之后重试。`,
});
return lastResult || empty;
}
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), fetchPayload);
} catch (e) {
report({
type: 'errorChecking',
message: '无法连接主更新服务器,尝试备用节点',
});
const backupEndpoints = await updateBackupEndpoints();
if (backupEndpoints) {
try {
resp = await promiseAny(
backupEndpoints.map((endpoint) =>
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
),
);
} catch {}
}
}
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) {
report({
type: 'errorChecking',
//@ts-ignore
message: result.message,
});
}
return result;
}
function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) {
return;
}
op.forEach((action) => {
if (action.type === 'block') {
blockUpdate = {
reason: action.reason,
until: Math.round((Date.now() + action.duration) / 1000),
};
PushyModule.setBlockUpdate(blockUpdate);
}
});
}
let downloadingThrottling = false;
let downloadedHash: string;
export async function downloadUpdate(
options: UpdateAvailableResult,
eventListeners?: {
onDownloadProgress?: (data: ProgressData) => void;
},
) {
assertRelease();
if (!options.update) {
return;
}
if (rolledBackVersion === options.hash) {
logger(`rolledback hash ${rolledBackVersion}, ignored`);
return;
}
if (downloadedHash === options.hash) {
logger(`duplicated downloaded hash ${downloadedHash}, ignored`);
return downloadedHash;
}
if (downloadingThrottling) {
logger('repeated downloading, ignored');
return;
}
downloadingThrottling = true;
setTimeout(() => {
downloadingThrottling = false;
}, 3000);
let progressHandler;
if (eventListeners) {
if (eventListeners.onDownloadProgress) {
const downloadCallback = eventListeners.onDownloadProgress;
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
if (progressData.hash === options.hash) {
downloadCallback(progressData);
}
},
);
}
}
let succeeded = false;
report({ type: 'downloading' });
const diffUrl = (await testUrls(options.diffUrls)) || options.diffUrl;
if (diffUrl) {
logger('downloading diff');
try {
await PushyModule.downloadPatchFromPpk({
updateUrl: diffUrl,
hash: options.hash,
originHash: currentVersion,
});
succeeded = true;
} catch (e) {
logger(`diff error: ${e.message}, try pdiff`);
}
}
if (!succeeded) {
const pdiffUrl = (await testUrls(options.pdiffUrls)) || options.pdiffUrl;
if (pdiffUrl) {
logger('downloading pdiff');
try {
await PushyModule.downloadPatchFromPackage({
updateUrl: pdiffUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`pdiff error: ${e.message}, try full patch`);
}
}
}
if (!succeeded) {
const updateUrl = (await testUrls(options.updateUrls)) || options.updateUrl;
if (updateUrl) {
logger('downloading full patch');
try {
await PushyModule.downloadFullUpdate({
updateUrl: updateUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`full patch error: ${e.message}`);
}
}
}
progressHandler && progressHandler.remove();
if (!succeeded) {
return report({ type: 'errorUpdate', data: { newVersion: options.hash } });
}
setLocalHashInfo(options.hash, {
name: options.name,
description: options.description,
metaInfo: options.metaInfo,
});
downloadedHash = options.hash;
return options.hash;
}
function assertHash(hash: string) {
if (!downloadedHash) {
logger(`no downloaded hash`);
return;
}
if (hash !== downloadedHash) {
logger(`use downloaded hash ${downloadedHash} first`);
return;
}
return true;
}
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
PushyModule.reloadUpdate({ hash });
}
}
export function switchVersionLater(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
PushyModule.setNeedUpdate({ hash });
}
}
let marked = false;
export function markSuccess() {
assertRelease();
if (marked) {
logger('repeated markSuccess, ignored');
return;
}
marked = true;
PushyModule.markSuccess();
report({ type: 'markSuccess' });
}
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 report({ type: 'rejectStoragePermission' });
}
} catch (err) {
return report({ type: 'errorStoragePermission' });
}
}
let hash = Date.now().toString();
let progressHandler;
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData: ProgressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
await PushyModule.downloadAndInstallApk({
url,
target: 'update.apk',
hash,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
});
progressHandler && progressHandler.remove();
}

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

74
lib/type.ts Normal file
View File

@@ -0,0 +1,74 @@
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;
pdiffUrls?: string[];
diffUrl?: string;
diffUrls?: string[];
updateUrl?: string;
updateUrls?: 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;

46
lib/utils.ts Normal file
View File

@@ -0,0 +1,46 @@
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[]) {
console.log('Pushy: ', ...args);
}
export function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
const ping =
Platform.OS === 'web'
? Promise.resolve
: async (url: string) =>
Promise.race([
fetch(url, {
method: 'HEAD',
}).then(({ status }) => (status === 200 ? url : null)),
new Promise(r => setTimeout(() => r(null), 2000)),
]);
export const testUrls = async (urls?: string[]) => {
if (!urls?.length) {
return null;
}
return promiseAny(urls.map(ping)).catch(() => null);
};

View File

@@ -1,8 +1,8 @@
{
"name": "react-native-update",
"version": "8.1.0",
"version": "8.5.2",
"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,17 @@
"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"
},
"packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72"
}

3819
yarn.lock

File diff suppressed because it is too large Load Diff