mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-16 11:31:37 +08:00
feat: ts
This commit is contained in:
@@ -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
53
lib/endpoint.ts
Normal 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
94
lib/index.d.ts
vendored
@@ -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;
|
|
@@ -14,4 +14,5 @@ export const markSuccess = noop;
|
|||||||
export const downloadAndInstallApk = noop;
|
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 = (app) => app;
|
||||||
|
export const onEvents = noop;
|
||||||
|
@@ -1,8 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
tryBackupEndpoints,
|
updateBackupEndpoints,
|
||||||
getCheckUrl,
|
getCheckUrl,
|
||||||
setCustomEndpoints,
|
setCustomEndpoints,
|
||||||
getReportUrl,
|
|
||||||
} from './endpoint';
|
} from './endpoint';
|
||||||
import {
|
import {
|
||||||
NativeEventEmitter,
|
NativeEventEmitter,
|
||||||
@@ -10,62 +9,71 @@ import {
|
|||||||
Platform,
|
Platform,
|
||||||
PermissionsAndroid,
|
PermissionsAndroid,
|
||||||
} from 'react-native';
|
} from 'react-native';
|
||||||
|
import {
|
||||||
|
CheckResult,
|
||||||
|
EventType,
|
||||||
|
ProgressData,
|
||||||
|
UpdateAvailableResult,
|
||||||
|
UpdateEventsListener,
|
||||||
|
} from './type';
|
||||||
|
import { assertRelease, logger } from './utils';
|
||||||
export { setCustomEndpoints };
|
export { setCustomEndpoints };
|
||||||
const {
|
const {
|
||||||
version: v,
|
version: v,
|
||||||
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||||
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
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模块无法加载,请对照安装文档检查配置。');
|
throw new Error('react-native-update模块无法加载,请对照安装文档检查配置。');
|
||||||
}
|
}
|
||||||
|
const PushyConstants = PushyModule;
|
||||||
|
|
||||||
export const downloadRootDir = Pushy.downloadRootDir;
|
export const downloadRootDir = PushyConstants.downloadRootDir;
|
||||||
export const packageVersion = Pushy.packageVersion;
|
export const packageVersion = PushyConstants.packageVersion;
|
||||||
export const currentVersion = Pushy.currentVersion;
|
export const currentVersion = PushyConstants.currentVersion;
|
||||||
export const isFirstTime = Pushy.isFirstTime;
|
export const isFirstTime = PushyConstants.isFirstTime;
|
||||||
const rolledBackVersion = Pushy.rolledBackVersion;
|
const rolledBackVersion = PushyConstants.rolledBackVersion;
|
||||||
export const isRolledBack = typeof rolledBackVersion === 'string';
|
export const isRolledBack = typeof rolledBackVersion === 'string';
|
||||||
|
|
||||||
export const buildTime = Pushy.buildTime;
|
export const buildTime = PushyConstants.buildTime;
|
||||||
let blockUpdate = Pushy.blockUpdate;
|
let blockUpdate = PushyConstants.blockUpdate;
|
||||||
let uuid = Pushy.uuid;
|
let uuid = PushyConstants.uuid;
|
||||||
|
|
||||||
if (Platform.OS === 'android' && !Pushy.isUsingBundleUrl) {
|
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'react-native-update模块无法加载,请对照文档检查Bundle URL的配置',
|
'react-native-update模块无法加载,请对照文档检查Bundle URL的配置',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setLocalHashInfo(hash, info) {
|
function setLocalHashInfo(hash: string, info: Record<string, any>) {
|
||||||
Pushy.setLocalHashInfo(hash, JSON.stringify(info));
|
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getLocalHashInfo(hash) {
|
async function getLocalHashInfo(hash: string) {
|
||||||
return JSON.parse(await Pushy.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)) || {} : {};
|
||||||
}
|
}
|
||||||
|
|
||||||
const eventEmitter = new NativeEventEmitter(Pushy);
|
const eventEmitter = new NativeEventEmitter(PushyModule);
|
||||||
|
|
||||||
if (!uuid) {
|
if (!uuid) {
|
||||||
uuid = require('nanoid/non-secure').nanoid();
|
uuid = require('nanoid/non-secure').nanoid();
|
||||||
Pushy.setUuid(uuid);
|
PushyModule.setUuid(uuid);
|
||||||
}
|
|
||||||
|
|
||||||
function logger(...args) {
|
|
||||||
console.log('Pushy: ', ...args);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const noop = () => {};
|
const noop = () => {};
|
||||||
let reporter = noop;
|
let reporter: UpdateEventsListener = noop;
|
||||||
|
|
||||||
export function onEvents(customReporter) {
|
export function onEvents(customReporter: UpdateEventsListener) {
|
||||||
reporter = customReporter;
|
reporter = customReporter;
|
||||||
if (isRolledBack) {
|
if (isRolledBack) {
|
||||||
report({
|
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);
|
logger(type + ' ' + message);
|
||||||
reporter({
|
reporter({
|
||||||
type,
|
type,
|
||||||
@@ -101,19 +117,10 @@ export const cInfo = {
|
|||||||
uuid,
|
uuid,
|
||||||
};
|
};
|
||||||
|
|
||||||
function assertRelease() {
|
|
||||||
if (__DEV__) {
|
|
||||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let lastChecking;
|
let lastChecking;
|
||||||
const empty = {};
|
const empty = {};
|
||||||
let lastResult;
|
let lastResult: CheckResult;
|
||||||
export async function checkUpdate(APPKEY, isRetry) {
|
export async function checkUpdate(APPKEY: string) {
|
||||||
if (typeof APPKEY !== 'string') {
|
|
||||||
throw new Error('未检查到合法的APPKEY,请查看update.json文件是否正确生成');
|
|
||||||
}
|
|
||||||
assertRelease();
|
assertRelease();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
|
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
|
||||||
@@ -131,40 +138,55 @@ export async function checkUpdate(APPKEY, isRetry) {
|
|||||||
return lastResult || empty;
|
return lastResult || empty;
|
||||||
}
|
}
|
||||||
report({ type: 'checking' });
|
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;
|
let resp;
|
||||||
try {
|
try {
|
||||||
resp = await fetch(getCheckUrl(APPKEY), {
|
resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
packageVersion,
|
|
||||||
hash: currentVersion,
|
|
||||||
buildTime,
|
|
||||||
cInfo,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (isRetry) {
|
report({
|
||||||
report({
|
type: 'errorChecking',
|
||||||
type: 'errorChecking',
|
message: '无法连接主更新服务器,尝试备用节点',
|
||||||
message: '无法连接更新服务器,请检查网络连接后重试',
|
});
|
||||||
});
|
const backupEndpoints = await updateBackupEndpoints();
|
||||||
return lastResult || empty;
|
if (backupEndpoints) {
|
||||||
|
try {
|
||||||
|
resp = await Promise.race(
|
||||||
|
backupEndpoints.map((endpoint) =>
|
||||||
|
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch {}
|
||||||
}
|
}
|
||||||
await tryBackupEndpoints();
|
|
||||||
return checkUpdate(APPKEY, true);
|
|
||||||
}
|
}
|
||||||
const result = await resp.json();
|
if (!resp) {
|
||||||
lastResult = result;
|
report({
|
||||||
|
type: 'errorChecking',
|
||||||
|
message: '无法连接更新服务器,请检查网络连接后重试',
|
||||||
|
});
|
||||||
|
return lastResult || empty;
|
||||||
|
}
|
||||||
|
const result: CheckResult = await resp.json();
|
||||||
|
|
||||||
|
lastResult = result;
|
||||||
|
// @ts-ignore
|
||||||
checkOperation(result.op);
|
checkOperation(result.op);
|
||||||
|
|
||||||
if (resp.status !== 200) {
|
if (resp.status !== 200) {
|
||||||
report({
|
report({
|
||||||
type: 'errorChecking',
|
type: 'errorChecking',
|
||||||
|
//@ts-ignore
|
||||||
message: result.message,
|
message: result.message,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -172,7 +194,9 @@ export async function checkUpdate(APPKEY, isRetry) {
|
|||||||
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;
|
||||||
}
|
}
|
||||||
@@ -182,14 +206,19 @@ function checkOperation(op) {
|
|||||||
reason: action.reason,
|
reason: action.reason,
|
||||||
until: Math.round((Date.now() + action.duration) / 1000),
|
until: Math.round((Date.now() + action.duration) / 1000),
|
||||||
};
|
};
|
||||||
Pushy.setBlockUpdate(blockUpdate);
|
PushyModule.setBlockUpdate(blockUpdate);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
@@ -229,7 +258,7 @@ export async function downloadUpdate(options, eventListeners) {
|
|||||||
if (options.diffUrl) {
|
if (options.diffUrl) {
|
||||||
logger('downloading diff');
|
logger('downloading diff');
|
||||||
try {
|
try {
|
||||||
await Pushy.downloadPatchFromPpk({
|
await PushyModule.downloadPatchFromPpk({
|
||||||
updateUrl: options.diffUrl,
|
updateUrl: options.diffUrl,
|
||||||
hash: options.hash,
|
hash: options.hash,
|
||||||
originHash: currentVersion,
|
originHash: currentVersion,
|
||||||
@@ -242,7 +271,7 @@ export async function downloadUpdate(options, eventListeners) {
|
|||||||
if (!succeeded && options.pdiffUrl) {
|
if (!succeeded && options.pdiffUrl) {
|
||||||
logger('downloading pdiff');
|
logger('downloading pdiff');
|
||||||
try {
|
try {
|
||||||
await Pushy.downloadPatchFromPackage({
|
await PushyModule.downloadPatchFromPackage({
|
||||||
updateUrl: options.pdiffUrl,
|
updateUrl: options.pdiffUrl,
|
||||||
hash: options.hash,
|
hash: options.hash,
|
||||||
});
|
});
|
||||||
@@ -254,7 +283,7 @@ export async function downloadUpdate(options, eventListeners) {
|
|||||||
if (!succeeded && options.updateUrl) {
|
if (!succeeded && options.updateUrl) {
|
||||||
logger('downloading full patch');
|
logger('downloading full patch');
|
||||||
try {
|
try {
|
||||||
await Pushy.downloadFullUpdate({
|
await PushyModule.downloadFullUpdate({
|
||||||
updateUrl: options.updateUrl,
|
updateUrl: options.updateUrl,
|
||||||
hash: options.hash,
|
hash: options.hash,
|
||||||
});
|
});
|
||||||
@@ -276,7 +305,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;
|
||||||
@@ -288,19 +317,19 @@ 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);
|
||||||
Pushy.reloadUpdate({ hash });
|
PushyModule.reloadUpdate({ hash });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function switchVersionLater(hash) {
|
export function switchVersionLater(hash: string) {
|
||||||
assertRelease();
|
assertRelease();
|
||||||
if (assertHash(hash)) {
|
if (assertHash(hash)) {
|
||||||
logger('switchVersionLater: ' + hash);
|
logger('switchVersionLater: ' + hash);
|
||||||
Pushy.setNeedUpdate({ hash });
|
PushyModule.setNeedUpdate({ hash });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -312,13 +341,22 @@ export function markSuccess() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
marked = true;
|
marked = true;
|
||||||
Pushy.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,
|
||||||
@@ -335,14 +373,14 @@ 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);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
await Pushy.downloadAndInstallApk({
|
await PushyModule.downloadAndInstallApk({
|
||||||
url,
|
url,
|
||||||
target: 'update.apk',
|
target: 'update.apk',
|
||||||
hash,
|
hash,
|
@@ -1,5 +1,11 @@
|
|||||||
import React, { Component } from 'react';
|
import React, { PureComponent, ComponentType } from 'react';
|
||||||
import { Platform, Alert, Linking, AppState } from 'react-native';
|
import {
|
||||||
|
Platform,
|
||||||
|
Alert,
|
||||||
|
Linking,
|
||||||
|
AppState,
|
||||||
|
NativeEventSubscription,
|
||||||
|
} from 'react-native';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
isFirstTime,
|
isFirstTime,
|
||||||
@@ -10,16 +16,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: ComponentType,
|
||||||
|
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);
|
||||||
|
}
|
||||||
return __DEV__
|
return __DEV__
|
||||||
? WrappedComponent
|
? WrappedComponent
|
||||||
: class AppUpdate extends Component {
|
: class AppUpdate extends PureComponent {
|
||||||
|
stateListener: NativeEventSubscription;
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
if (isRolledBack) {
|
if (isRolledBack) {
|
||||||
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
|
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
|
||||||
@@ -70,7 +85,7 @@ export function simpleUpdate(WrappedComponent, options = {}) {
|
|||||||
checkUpdate = async () => {
|
checkUpdate = async () => {
|
||||||
let info;
|
let info;
|
||||||
try {
|
try {
|
||||||
info = await checkUpdate(appKey);
|
info = await checkUpdate(appKey!);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
Alert.alert('更新检查失败', err.message);
|
Alert.alert('更新检查失败', err.message);
|
||||||
return;
|
return;
|
71
lib/type.ts
Normal file
71
lib/type.ts
Normal 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
9
lib/utils.ts
Normal 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 版本中运行.');
|
||||||
|
}
|
||||||
|
}
|
10
package.json
10
package.json
@@ -2,7 +2,7 @@
|
|||||||
"name": "react-native-update",
|
"name": "react-native-update",
|
||||||
"version": "8.2.0",
|
"version": "8.2.0",
|
||||||
"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",
|
||||||
@@ -25,10 +25,16 @@
|
|||||||
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
|
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react-native": ">=0.27.0"
|
"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": {
|
||||||
"nanoid": "^3.3.3"
|
"nanoid": "^3.3.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.8.9",
|
||||||
|
"@types/react": "^18.2.33",
|
||||||
|
"react-native": "^0.72.6",
|
||||||
|
"typescript": "^5.2.2"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user