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

feat: onEvents

This commit is contained in:
sunnylqm
2023-08-31 19:24:00 +08:00
parent f1e9244a14
commit 39c4a6d339
8 changed files with 201 additions and 160 deletions

View File

@@ -1,6 +1,6 @@
let currentEndpoint = 'https://update.react-native.cn/api'; let currentEndpoint = 'https://update.react-native.cn/api';
function ping(url, rejectImmediate) { function ping(url: string, rejectImmediate?: boolean) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => { xhr.onreadystatechange = (e) => {
@@ -20,12 +20,12 @@ function ping(url, rejectImmediate) {
}); });
} }
function logger(...args) { function logger(...args: any[]) {
// console.warn('pushy', ...args); console.log('Pushy: ', ...args);
} }
let backupEndpoints = []; let backupEndpoints: string[] = [];
let backupEndpointsQueryUrl = let backupEndpointsQueryUrl: string | null =
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json'; 'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json';
export async function tryBackupEndpoints() { export async function tryBackupEndpoints() {
@@ -34,10 +34,10 @@ export async function tryBackupEndpoints() {
} }
try { try {
await ping(getStatusUrl(), true); await ping(getStatusUrl(), true);
logger('current endpoint ok'); logger('current endpoint ok', currentEndpoint);
return; return;
} catch (e) { } catch (e) {
logger('current endpoint failed'); logger('current endpoint failed', currentEndpoint);
} }
if (!backupEndpoints.length && backupEndpointsQueryUrl) { if (!backupEndpoints.length && backupEndpointsQueryUrl) {
try { try {
@@ -76,11 +76,21 @@ export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
return `${endpoint}/checkUpdate/${APPKEY}`; return `${endpoint}/checkUpdate/${APPKEY}`;
} }
export function getReportUrl(endpoint = currentEndpoint) { /**
return `${endpoint}/report`; * @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.
export function setCustomEndpoints({ main, backups, backupQueryUrl }) { * like: ["https://backup.api/1", "https://backup.api/2"]
*/
export function setCustomEndpoints({
main,
backups,
backupQueryUrl,
}: {
main: string;
backups?: string[];
backupQueryUrl?: string;
}) {
currentEndpoint = main; currentEndpoint = main;
backupEndpointsQueryUrl = null; backupEndpointsQueryUrl = null;
if (Array.isArray(backups) && backups.length > 0) { if (Array.isArray(backups) && backups.length > 0) {

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

@@ -15,3 +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 = noop; export const simpleUpdate = noop;
export const onEvents = noop;

View File

@@ -2,7 +2,6 @@ import {
tryBackupEndpoints, tryBackupEndpoints,
getCheckUrl, getCheckUrl,
setCustomEndpoints, setCustomEndpoints,
getReportUrl,
} from './endpoint'; } from './endpoint';
import { import {
NativeEventEmitter, NativeEventEmitter,
@@ -10,6 +9,12 @@ import {
Platform, Platform,
PermissionsAndroid, PermissionsAndroid,
} from 'react-native'; } from 'react-native';
import {
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
export { setCustomEndpoints }; export { setCustomEndpoints };
const { const {
version: v, version: v,
@@ -45,15 +50,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)); PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
} }
async function getLocalHashInfo(hash) { async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash)); 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)) || {} : {}; return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
} }
@@ -64,34 +73,50 @@ if (!uuid) {
PushyModule.setUuid(uuid); PushyModule.setUuid(uuid);
} }
function logger(text) { function logger(...args: string[]) {
console.log(`Pushy: ${text}`); console.log('Pushy: ', ...args);
} }
function report(hash, type) { const noop = () => {};
logger(type); let reporter: UpdateEventsListener = noop;
fetch(getReportUrl(), {
method: 'POST', export function onEvents(customReporter: UpdateEventsListener) {
headers: { reporter = customReporter;
Accept: 'application/json', if (isRolledBack) {
'Content-Type': 'application/json', report({
type: 'rollback',
data: {
rolledBackVersion,
}, },
body: JSON.stringify({ });
hash, }
}
function report({
type, type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
logger(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo, cInfo,
packageVersion, packageVersion,
buildTime, buildTime,
}), message,
}).catch((_e) => {}); ...data,
},
});
} }
logger('uuid: ' + uuid); logger('uuid: ' + uuid);
if (isRolledBack) {
report(rolledBackVersion, 'rollback');
}
export const cInfo = { export const cInfo = {
pushy: require('../package.json').version, pushy: require('../package.json').version,
rn: RNVersion, rn: RNVersion,
@@ -100,13 +125,14 @@ export const cInfo = {
}; };
function assertRelease() { function assertRelease() {
// @ts-expect-error
if (__DEV__) { if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.'); throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
} }
} }
let checkingThrottling = false; let checkingThrottling = false;
export async function checkUpdate(APPKEY, isRetry) { export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
assertRelease(); assertRelease();
if (checkingThrottling) { if (checkingThrottling) {
logger('repeated checking, ignored'); logger('repeated checking, ignored');
@@ -117,16 +143,14 @@ export async function checkUpdate(APPKEY, isRetry) {
checkingThrottling = false; checkingThrottling = false;
}, 3000); }, 3000);
if (blockUpdate && blockUpdate.until > Date.now() / 1000) { if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
throw new Error( return report({
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date( type: 'errorChecking',
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000, blockUpdate.until * 1000,
).toLocaleString()}"`, ).toLocaleString()}"`,
); });
} }
if (typeof APPKEY !== 'string') { report({ type: 'checking' });
throw new Error('未检查到合法的APPKEY请查看update.json文件是否正确生成');
}
logger('checking update');
let resp; let resp;
try { try {
resp = await fetch(getCheckUrl(APPKEY), { resp = await fetch(getCheckUrl(APPKEY), {
@@ -144,7 +168,10 @@ export async function checkUpdate(APPKEY, isRetry) {
}); });
} catch (e) { } catch (e) {
if (isRetry) { if (isRetry) {
throw new Error('无法连接更新服务器,请检查网络连接后重试'); return report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
} }
await tryBackupEndpoints(); await tryBackupEndpoints();
return checkUpdate(APPKEY, true); return checkUpdate(APPKEY, true);
@@ -153,13 +180,15 @@ export async function checkUpdate(APPKEY, isRetry) {
checkOperation(result.op); checkOperation(result.op);
if (resp.status !== 200) { if (resp.status !== 200) {
throw new Error(result.message); return report({ type: 'errorChecking', message: result.message });
} }
return result; return result;
} }
function checkOperation(op) { function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) { if (!Array.isArray(op)) {
return; return;
} }
@@ -175,8 +204,13 @@ function checkOperation(op) {
} }
let downloadingThrottling = false; let downloadingThrottling = false;
let downloadedHash; let downloadedHash: string;
export async function downloadUpdate(options, eventListeners) { export async function downloadUpdate(
options: UpdateAvailableResult,
eventListeners?: {
onDownloadProgress?: (data: ProgressData) => void;
},
) {
assertRelease(); assertRelease();
if (!options.update) { if (!options.update) {
return; return;
@@ -212,6 +246,7 @@ export async function downloadUpdate(options, eventListeners) {
} }
} }
let succeeded = false; let succeeded = false;
report({ type: 'downloading' });
if (options.diffUrl) { if (options.diffUrl) {
logger('downloading diff'); logger('downloading diff');
try { try {
@@ -251,8 +286,7 @@ export async function downloadUpdate(options, eventListeners) {
} }
progressHandler && progressHandler.remove(); progressHandler && progressHandler.remove();
if (!succeeded) { if (!succeeded) {
report(options.hash, 'error'); return report({ type: 'errorUpdate', data: { newVersion: options.hash } });
throw new Error('all update attempts failed');
} }
setLocalHashInfo(options.hash, { setLocalHashInfo(options.hash, {
name: options.name, name: options.name,
@@ -263,7 +297,7 @@ export async function downloadUpdate(options, eventListeners) {
return options.hash; return options.hash;
} }
function assertHash(hash) { function assertHash(hash: string) {
if (!downloadedHash) { if (!downloadedHash) {
logger(`no downloaded hash`); logger(`no downloaded hash`);
return; return;
@@ -275,7 +309,7 @@ function assertHash(hash) {
return true; return true;
} }
export function switchVersion(hash) { export function switchVersion(hash: string) {
assertRelease(); assertRelease();
if (assertHash(hash)) { if (assertHash(hash)) {
logger('switchVersion: ' + hash); logger('switchVersion: ' + hash);
@@ -283,7 +317,7 @@ export function switchVersion(hash) {
} }
} }
export function switchVersionLater(hash) { export function switchVersionLater(hash: string) {
assertRelease(); assertRelease();
if (assertHash(hash)) { if (assertHash(hash)) {
logger('switchVersionLater: ' + hash); logger('switchVersionLater: ' + hash);
@@ -300,21 +334,30 @@ export function markSuccess() {
} }
marked = true; marked = true;
PushyModule.markSuccess(); PushyModule.markSuccess();
report(currentVersion, 'success'); report({ type: 'markSuccess' });
} }
export async function downloadAndInstallApk({ url, onDownloadProgress }) { export async function downloadAndInstallApk({
logger('downloadAndInstallApk'); url,
if (Platform.OS === 'android' && Platform.Version <= 23) { onDownloadProgress,
}: {
url: string;
onDownloadProgress?: (data: ProgressData) => void;
}) {
if (Platform.OS !== 'android') {
return;
}
report({ type: 'downloadingApk' });
if (Platform.Version <= 23) {
try { try {
const granted = await PermissionsAndroid.request( const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
); );
if (granted !== PermissionsAndroid.RESULTS.GRANTED) { if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return; return report({ type: 'rejectStoragePermission' });
} }
} catch (err) { } catch (err) {
console.warn(err); return report({ type: 'errorStoragePermission' });
} }
} }
let hash = Date.now().toString(); let hash = Date.now().toString();
@@ -322,7 +365,7 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
if (onDownloadProgress) { if (onDownloadProgress) {
progressHandler = eventEmitter.addListener( progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress', 'RCTPushyDownloadProgress',
(progressData) => { (progressData: ProgressData) => {
if (progressData.hash === hash) { if (progressData.hash === hash) {
onDownloadProgress(progressData); onDownloadProgress(progressData);
} }
@@ -333,6 +376,8 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
url, url,
target: 'update.apk', target: 'update.apk',
hash, hash,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
}); });
progressHandler && progressHandler.remove(); progressHandler && progressHandler.remove();
} }

View File

@@ -1,4 +1,4 @@
import React, { Component } from 'react'; import React, { PureComponent } from 'react';
import { Platform, Alert, Linking, AppState } from 'react-native'; import { Platform, Alert, Linking, AppState } from 'react-native';
import { import {
@@ -10,16 +10,25 @@ import {
switchVersionLater, switchVersionLater,
markSuccess, markSuccess,
downloadAndInstallApk, downloadAndInstallApk,
onEvents,
} from './main'; } from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(WrappedComponent, options = {}) { export function simpleUpdate(
const { appKey } = options; WrappedComponent: JSX.Element,
options: { appKey?: string; onEvents?: UpdateEventsListener } = {},
) {
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') {
onEvents(eventListeners);
}
// @ts-expect-error
return __DEV__ return __DEV__
? WrappedComponent ? WrappedComponent
: class AppUpdate extends Component { : class AppUpdate extends PureComponent {
componentDidMount() { componentDidMount() {
if (isRolledBack) { if (isRolledBack) {
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本'); Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');

70
lib/type.ts Normal file
View File

@@ -0,0 +1,70 @@
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;

View File

@@ -1,8 +1,8 @@
{ {
"name": "react-native-update", "name": "react-native-update",
"version": "9.0.0-beta.0", "version": "9.0.0-beta.1",
"description": "react-native hot update", "description": "react-native hot update",
"main": "lib/index.js", "main": "lib/index.ts",
"scripts": { "scripts": {
"prepublish": "yarn submodule", "prepublish": "yarn submodule",
"submodule": "git submodule update --init --recursive", "submodule": "git submodule update --init --recursive",