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

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 getCurrentVersionInfo = noop;
export const simpleUpdate = noop;
export const onEvents = noop;

View File

@@ -2,7 +2,6 @@ import {
tryBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
getReportUrl,
} from './endpoint';
import {
NativeEventEmitter,
@@ -10,6 +9,12 @@ import {
Platform,
PermissionsAndroid,
} from 'react-native';
import {
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
export { setCustomEndpoints };
const {
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));
}
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 +73,50 @@ if (!uuid) {
PushyModule.setUuid(uuid);
}
function logger(text) {
console.log(`Pushy: ${text}`);
function logger(...args: string[]) {
console.log('Pushy: ', ...args);
}
function report(hash, type) {
logger(type);
fetch(getReportUrl(), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
hash,
type,
const noop = () => {};
let reporter: UpdateEventsListener = noop;
export function onEvents(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,
}),
}).catch((_e) => {});
message,
...data,
},
});
}
logger('uuid: ' + uuid);
if (isRolledBack) {
report(rolledBackVersion, 'rollback');
}
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
@@ -100,13 +125,14 @@ export const cInfo = {
};
function assertRelease() {
// @ts-expect-error
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
let checkingThrottling = false;
export async function checkUpdate(APPKEY, isRetry) {
export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
assertRelease();
if (checkingThrottling) {
logger('repeated checking, ignored');
@@ -117,16 +143,14 @@ export async function checkUpdate(APPKEY, isRetry) {
checkingThrottling = false;
}, 3000);
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
throw new Error(
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
return report({
type: 'errorChecking',
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"`,
);
});
}
if (typeof APPKEY !== 'string') {
throw new Error('未检查到合法的APPKEY请查看update.json文件是否正确生成');
}
logger('checking update');
report({ type: 'checking' });
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), {
@@ -144,7 +168,10 @@ export async function checkUpdate(APPKEY, isRetry) {
});
} catch (e) {
if (isRetry) {
throw new Error('无法连接更新服务器,请检查网络连接后重试');
return report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
}
await tryBackupEndpoints();
return checkUpdate(APPKEY, true);
@@ -153,13 +180,15 @@ export async function checkUpdate(APPKEY, isRetry) {
checkOperation(result.op);
if (resp.status !== 200) {
throw new Error(result.message);
return report({ type: 'errorChecking', message: result.message });
}
return result;
}
function checkOperation(op) {
function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) {
return;
}
@@ -175,8 +204,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 +246,7 @@ export async function downloadUpdate(options, eventListeners) {
}
}
let succeeded = false;
report({ type: 'downloading' });
if (options.diffUrl) {
logger('downloading diff');
try {
@@ -251,8 +286,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 +297,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,7 +309,7 @@ function assertHash(hash) {
return true;
}
export function switchVersion(hash) {
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
@@ -283,7 +317,7 @@ export function switchVersion(hash) {
}
}
export function switchVersionLater(hash) {
export function switchVersionLater(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
@@ -300,21 +334,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 +365,7 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
(progressData: ProgressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
@@ -333,6 +376,8 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
url,
target: 'update.apk',
hash,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
});
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 {
@@ -10,16 +10,25 @@ import {
switchVersionLater,
markSuccess,
downloadAndInstallApk,
onEvents,
} from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(WrappedComponent, options = {}) {
const { appKey } = options;
export function simpleUpdate(
WrappedComponent: JSX.Element,
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);
}
// @ts-expect-error
return __DEV__
? WrappedComponent
: class AppUpdate extends Component {
: class AppUpdate extends PureComponent {
componentDidMount() {
if (isRolledBack) {
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",
"version": "9.0.0-beta.0",
"version": "9.0.0-beta.1",
"description": "react-native hot update",
"main": "lib/index.js",
"main": "lib/index.ts",
"scripts": {
"prepublish": "yarn submodule",
"submodule": "git submodule update --init --recursive",