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

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
4231d377e6 v10.0.2 2024-02-19 11:41:47 +08:00
9 changed files with 77 additions and 128 deletions

View File

@@ -18,7 +18,7 @@
"react-native": "0.69.8", "react-native": "0.69.8",
"react-native-paper": "^5.12.1", "react-native-paper": "^5.12.1",
"react-native-safe-area-context": "^4.8.2", "react-native-safe-area-context": "^4.8.2",
"react-native-update": "^10.0.2", "react-native-update": "^10.0.0-beta.3",
"react-native-vector-icons": "^10.0.3" "react-native-vector-icons": "^10.0.3"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -6231,10 +6231,10 @@ react-native-safe-area-context@^4.8.2:
resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65" resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65"
integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ== integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ==
react-native-update@^10.0.2: react-native-update@^10.0.0-beta.3:
version "10.0.2" version "10.0.0-beta.3"
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.2.tgz#2bb01ab6e41e72bbbb535cebd34083b1fed69eb0" resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.0-beta.3.tgz#cad099ebb40ff04b31ba2df13930517039e4fae3"
integrity sha512-XkEPmTC3X6FV1eXq6uDyjfhXpAaug0HI48Mm+PkbMlXcgFjTrOmtuq7yuvemS2nPG2pwnrYQuGs0A6tE2aoRBA== integrity sha512-Ak1ylgHbOUeaNsq3ItZGRenqqAwYKSTlB6T4sBn4PPNGaMmIMt6uIKKWrQqcNyc9WEy9LlFM6kSqQXBQdaVatw==
dependencies: dependencies:
nanoid "^3.3.3" nanoid "^3.3.3"

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-native-update", "name": "react-native-update",
"version": "10.2.4", "version": "10.0.2",
"description": "react-native hot update", "description": "react-native hot update",
"main": "src/index.ts", "main": "src/index.ts",
"scripts": { "scripts": {

View File

@@ -1,5 +1,5 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type'; import { CheckResult, PushyOptions, ProgressData } from './type';
import { assertRelease, log, testUrls } from './utils'; import { assertRelease, log } from './utils';
import { import {
EmitterSubscription, EmitterSubscription,
PermissionsAndroid, PermissionsAndroid,
@@ -12,9 +12,9 @@ import {
pushyNativeEventEmitter, pushyNativeEventEmitter,
currentVersion, currentVersion,
packageVersion, packageVersion,
report,
rolledBackVersion, rolledBackVersion,
setLocalHashInfo, setLocalHashInfo,
isRolledBack,
} from './core'; } from './core';
const defaultServer = { const defaultServer = {
@@ -25,8 +25,6 @@ const defaultServer = {
}; };
const empty = {}; const empty = {};
const noop = () => {};
export class Pushy { export class Pushy {
options: PushyOptions = { options: PushyOptions = {
appKey: '', appKey: '',
@@ -34,11 +32,10 @@ export class Pushy {
autoMarkSuccess: true, autoMarkSuccess: true,
useAlert: true, useAlert: true,
strategy: 'both', strategy: 'both',
logger: noop,
}; };
lastChecking: number; lastChecking: number;
lastRespJson?: Promise<any>; lastResult: CheckResult;
progressHandlers: Record<string, EmitterSubscription> = {}; progressHandlers: Record<string, EmitterSubscription> = {};
downloadedHash: string; downloadedHash: string;
@@ -58,45 +55,10 @@ export class Pushy {
for (const [key, value] of Object.entries(options)) { for (const [key, value] of Object.entries(options)) {
if (value !== undefined) { if (value !== undefined) {
this.options[key] = value; this.options[key] = value;
if (key === 'logger') {
if (isRolledBack) {
this.report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
} }
} }
}; };
report = ({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) => {
log(type + ' ' + message);
const { logger = noop, appKey } = this.options;
logger({
type,
data: {
appKey,
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
};
getCheckUrl = (endpoint: string = this.options.server!.main) => { getCheckUrl = (endpoint: string = this.options.server!.main) => {
return `${endpoint}/checkUpdate/${this.options.appKey}`; return `${endpoint}/checkUpdate/${this.options.appKey}`;
}; };
@@ -117,7 +79,7 @@ export class Pushy {
} }
this.marked = true; this.marked = true;
PushyModule.markSuccess(); PushyModule.markSuccess();
this.report({ type: 'markSuccess' }); report({ type: 'markSuccess' });
}; };
switchVersion = (hash: string) => { switchVersion = (hash: string) => {
assertRelease(); assertRelease();
@@ -139,14 +101,14 @@ export class Pushy {
assertRelease(); assertRelease();
const now = Date.now(); const now = Date.now();
if ( if (
this.lastRespJson && this.lastResult &&
this.lastChecking && this.lastChecking &&
now - this.lastChecking < 1000 * 5 now - this.lastChecking < 1000 * 5
) { ) {
return await this.lastRespJson; return this.lastResult;
} }
this.lastChecking = now; this.lastChecking = now;
this.report({ type: 'checking' }); report({ type: 'checking' });
const fetchPayload = { const fetchPayload = {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -164,7 +126,7 @@ export class Pushy {
try { try {
resp = await fetch(this.getCheckUrl(), fetchPayload); resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e) { } catch (e) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: 'Can not connect to update server. Trying backup endpoints.', message: 'Can not connect to update server. Trying backup endpoints.',
}); });
@@ -180,18 +142,18 @@ export class Pushy {
} }
} }
if (!resp) { if (!resp) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: 'Can not connect to update server. Please check your network.', message: 'Can not connect to update server. Please check your network.',
}); });
return this.lastRespJson ? await this.lastRespJson : empty; return this.lastResult || empty;
} }
this.lastRespJson = resp.json(); const result: CheckResult = await resp.json();
const result: CheckResult = await this.lastRespJson; this.lastResult = result;
if (resp.status !== 200) { if (resp.status !== 200) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: result.message, message: result.message,
}); });
@@ -225,18 +187,8 @@ export class Pushy {
onDownloadProgress?: (data: ProgressData) => void, onDownloadProgress?: (data: ProgressData) => void,
) => { ) => {
assertRelease(); assertRelease();
const { const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
hash, info;
diffUrl: _diffUrl,
diffUrls,
pdiffUrl: _pdiffUrl,
pdiffUrls,
updateUrl: _updateUrl,
updateUrls,
name,
description,
metaInfo,
} = info;
if (!info.update || !hash) { if (!info.update || !hash) {
return; return;
} }
@@ -262,8 +214,7 @@ export class Pushy {
); );
} }
let succeeded = false; let succeeded = false;
this.report({ type: 'downloading' }); report({ type: 'downloading' });
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
if (diffUrl) { if (diffUrl) {
log('downloading diff'); log('downloading diff');
try { try {
@@ -277,7 +228,6 @@ export class Pushy {
log(`diff error: ${e.message}, try pdiff`); log(`diff error: ${e.message}, try pdiff`);
} }
} }
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
if (!succeeded && pdiffUrl) { if (!succeeded && pdiffUrl) {
log('downloading pdiff'); log('downloading pdiff');
try { try {
@@ -290,7 +240,6 @@ export class Pushy {
log(`pdiff error: ${e.message}, try full patch`); log(`pdiff error: ${e.message}, try full patch`);
} }
} }
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
if (!succeeded && updateUrl) { if (!succeeded && updateUrl) {
log('downloading full patch'); log('downloading full patch');
try { try {
@@ -308,7 +257,7 @@ export class Pushy {
delete this.progressHandlers[hash]; delete this.progressHandlers[hash];
} }
if (!succeeded) { if (!succeeded) {
return this.report({ return report({
type: 'errorUpdate', type: 'errorUpdate',
data: { newVersion: hash }, data: { newVersion: hash },
}); });
@@ -329,17 +278,17 @@ export class Pushy {
if (Platform.OS !== 'android') { if (Platform.OS !== 'android') {
return; return;
} }
this.report({ type: 'downloadingApk' }); report({ type: 'downloadingApk' });
if (Platform.Version <= 23) { 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 this.report({ type: 'rejectStoragePermission' }); return report({ type: 'rejectStoragePermission' });
} }
} catch (err) { } catch (err) {
return this.report({ type: 'errorStoragePermission' }); return report({ type: 'errorStoragePermission' });
} }
} }
const progressKey = 'downloadingApk'; const progressKey = 'downloadingApk';
@@ -358,7 +307,7 @@ export class Pushy {
target: 'update.apk', target: 'update.apk',
hash: progressKey, hash: progressKey,
}).catch(() => { }).catch(() => {
this.report({ type: 'errowDownloadAndInstallApk' }); report({ type: 'errowDownloadAndInstallApk' });
}); });
if (this.progressHandlers[progressKey]) { if (this.progressHandlers[progressKey]) {
this.progressHandlers[progressKey].remove(); this.progressHandlers[progressKey].remove();

View File

@@ -2,35 +2,29 @@ import { createContext, useContext } from 'react';
import { CheckResult, ProgressData } from './type'; import { CheckResult, ProgressData } from './type';
import { Pushy } from './client'; import { Pushy } from './client';
const empty = {};
const noop = () => {}; const noop = () => {};
const asyncNoop = () => Promise.resolve();
export const defaultContext = { export const defaultContext = {
checkUpdate: asyncNoop, checkUpdate: () => Promise.resolve(empty),
switchVersion: noop, switchVersion: noop,
switchVersionLater: noop, switchVersionLater: noop,
markSuccess: noop, markSuccess: noop,
dismissError: noop, dismissError: noop,
downloadUpdate: asyncNoop, downloadUpdate: noop,
downloadAndInstallApk: asyncNoop, downloadAndInstallApk: noop,
getCurrentVersionInfo: () => Promise.resolve({}),
currentHash: '', currentHash: '',
packageVersion: '', packageVersion: '',
}; };
export const PushyContext = createContext<{ export const PushyContext = createContext<{
checkUpdate: () => Promise<void>; checkUpdate: () => void;
switchVersion: () => void; switchVersion: () => void;
switchVersionLater: () => void; switchVersionLater: () => void;
markSuccess: () => void; markSuccess: () => void;
dismissError: () => void; dismissError: () => void;
downloadUpdate: () => Promise<void>; downloadUpdate: () => void;
downloadAndInstallApk: (url: string) => Promise<void>; downloadAndInstallApk: (url: string) => void;
getCurrentVersionInfo: () => Promise<{
name?: string;
description?: string;
metaInfo?: string;
}>;
currentHash: string; currentHash: string;
packageVersion: string; packageVersion: string;
client?: Pushy; client?: Pushy;

View File

@@ -1,4 +1,5 @@
import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { EventType, UpdateEventsLogger } from './type';
import { log } from './utils'; import { log } from './utils';
const { const {
version: v, version: v,
@@ -57,6 +58,44 @@ if (!uuid) {
PushyModule.setUuid(uuid); PushyModule.setUuid(uuid);
} }
const noop = () => {};
let reporter: UpdateEventsLogger = noop;
export function onPushyEvents(customReporter: UpdateEventsLogger) {
reporter = customReporter;
if (isRolledBack) {
report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
export function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
log(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
}
log('uuid: ' + uuid); log('uuid: ' + uuid);
export const cInfo = { export const cInfo = {

View File

@@ -13,12 +13,7 @@ import {
Linking, Linking,
} from 'react-native'; } from 'react-native';
import { Pushy } from './client'; import { Pushy } from './client';
import { import { currentVersion, isFirstTime, packageVersion } from './core';
currentVersion,
isFirstTime,
packageVersion,
getCurrentVersionInfo,
} from './core';
import { CheckResult, ProgressData } from './type'; import { CheckResult, ProgressData } from './type';
import { PushyContext } from './context'; import { PushyContext } from './context';
@@ -93,9 +88,9 @@ export const PushyProvider = ({
}, [client, showAlert, updateInfo]); }, [client, showAlert, updateInfo]);
const downloadAndInstallApk = useCallback( const downloadAndInstallApk = useCallback(
async (downloadUrl: string) => { (downloadUrl: string) => {
if (Platform.OS === 'android' && downloadUrl) { if (Platform.OS === 'android' && downloadUrl) {
await client.downloadAndInstallApk(downloadUrl, setProgress); client.downloadAndInstallApk(downloadUrl, setProgress);
} }
}, },
[client], [client],
@@ -148,10 +143,6 @@ export const PushyProvider = ({
const markSuccess = client.markSuccess; const markSuccess = client.markSuccess;
useEffect(() => { useEffect(() => {
if (__DEV__) {
console.info('检测到在DEV环境不会进行热更新检查');
return;
}
const { strategy, dismissErrorAfter, autoMarkSuccess } = options; const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
if (isFirstTime && autoMarkSuccess) { if (isFirstTime && autoMarkSuccess) {
markSuccess(); markSuccess();
@@ -197,7 +188,6 @@ export const PushyProvider = ({
currentHash: currentVersion, currentHash: currentVersion,
progress, progress,
downloadAndInstallApk, downloadAndInstallApk,
getCurrentVersionInfo,
}} }}
> >
{children} {children}

View File

@@ -8,11 +8,8 @@ export interface CheckResult {
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[];
paused?: 'app' | 'package'; paused?: 'app' | 'package';
message?: string; message?: string;
} }

View File

@@ -7,23 +7,3 @@ export function assertRelease() {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.'); throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
} }
} }
const ping = async (url: string) =>
Promise.race([
fetch(url, {
method: 'HEAD',
redirect: 'follow',
}).then(({ status }) => status === 200),
new Promise<false>((r) => setTimeout(() => r(false), 2000)),
]);
const canUseGoogle = ping('https://www.google.com');
export const testUrls = async (urls?: string[]) => {
if (!urls?.length || (await canUseGoogle)) {
return null;
}
return Promise.race(urls.map((url) => ping(url).then(() => url))).catch(
() => null,
);
};