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

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
f595b2d957 v10.0.0-beta.2 2024-01-25 22:07:01 +08:00
9 changed files with 85 additions and 107 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.1",
"react-native-vector-icons": "^10.0.3" "react-native-vector-icons": "^10.0.3"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -33,8 +33,7 @@ function App() {
const [showUpdateBanner, setShowUpdateBanner] = useState(false); const [showUpdateBanner, setShowUpdateBanner] = useState(false);
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false); const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
const snackbarVisible = const snackbarVisible =
!useDefaultAlert && showUpdateSnackbar && updateInfo?.update; showUpdateSnackbar && updateInfo?.update && !useDefaultAlert;
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.welcome}>使Pushy热更新服务</Text> <Text style={styles.welcome}>使Pushy热更新服务</Text>
@@ -49,7 +48,6 @@ function App() {
client?.setOptions({ client?.setOptions({
useAlert: v, useAlert: v,
}); });
setShowUpdateSnackbar(!v);
}} }}
/> />
</View> </View>
@@ -68,11 +66,7 @@ function App() {
<Text> <Text>
{received} / {total} {received} / {total}
</Text> </Text>
<TouchableOpacity <TouchableOpacity onPress={checkUpdate}>
onPress={() => {
checkUpdate();
setShowUpdateSnackbar(true);
}}>
<Text style={styles.instructions}></Text> <Text style={styles.instructions}></Text>
</TouchableOpacity> </TouchableOpacity>
@@ -89,7 +83,7 @@ function App() {
<TestConsole visible={showTestConsole} /> <TestConsole visible={showTestConsole} />
{snackbarVisible && ( {snackbarVisible && (
<Snackbar <Snackbar
visible={snackbarVisible} visible={true}
onDismiss={() => { onDismiss={() => {
setShowUpdateSnackbar(false); setShowUpdateSnackbar(false);
}} }}
@@ -101,13 +95,10 @@ function App() {
setShowUpdateBanner(true); setShowUpdateBanner(true);
}, },
}}> }}>
<Text style={{color: 'white'}}> <Text>({updateInfo.version})</Text>
({updateInfo.name})
</Text>
</Snackbar> </Snackbar>
)} )}
<Banner <Banner
style={{width: '100%', position: 'absolute', top: 0}}
visible={showUpdateBanner} visible={showUpdateBanner}
actions={[ actions={[
{ {

View File

@@ -1,10 +1,10 @@
{ {
"ios": { "ios": {
"appId": 24794, "appId": 24794,
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T" "appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
}, },
"android": { "android": {
"appId": 27509, "appId": 10977,
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY" "appKey": "bUYKfZgtC9VirZsQbAt8qken2Gq2uxe3"
} }
} }

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.1:
version "10.0.2" version "10.0.0-beta.1"
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.1.tgz#bc49a7197dd19c16ba798ea13324b4b292edd052"
integrity sha512-XkEPmTC3X6FV1eXq6uDyjfhXpAaug0HI48Mm+PkbMlXcgFjTrOmtuq7yuvemS2nPG2pwnrYQuGs0A6tE2aoRBA== integrity sha512-PFTsut8SL+vqAPtBUzPg9KKU9mFgCktKttifzM8B4puSoburlSN2UnD+eDWxLkXyIWQtoQAqAmXPE1/zA/e7dw==
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.1.0", "version": "10.0.0-beta.2",
"description": "react-native hot update", "description": "react-native hot update",
"main": "src/index.ts", "main": "src/index.ts",
"scripts": { "scripts": {

View File

@@ -1,4 +1,4 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type'; import { CheckResult, PushyOptions, ProgressData } from './type';
import { assertRelease, log } from './utils'; import { assertRelease, log } from './utils';
import { import {
EmitterSubscription, EmitterSubscription,
@@ -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,16 +25,12 @@ const defaultServer = {
}; };
const empty = {}; const empty = {};
const noop = () => {};
export class Pushy { export class Pushy {
options: PushyOptions = { options: PushyOptions = {
appKey: '', appKey: '',
server: defaultServer, server: defaultServer,
autoMarkSuccess: true, autoMarkSuccess: true,
useAlert: true, useAlert: true,
strategy: 'both',
logger: noop,
}; };
lastChecking: number; lastChecking: number;
@@ -58,45 +54,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 +78,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();
@@ -146,7 +107,7 @@ export class Pushy {
return this.lastResult; 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 +125,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,7 +141,7 @@ 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.',
}); });
@@ -191,7 +152,7 @@ export class Pushy {
this.lastResult = result; this.lastResult = result;
if (resp.status !== 200) { if (resp.status !== 200) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: result.message, message: result.message,
}); });
@@ -252,7 +213,7 @@ export class Pushy {
); );
} }
let succeeded = false; let succeeded = false;
this.report({ type: 'downloading' }); report({ type: 'downloading' });
if (diffUrl) { if (diffUrl) {
log('downloading diff'); log('downloading diff');
try { try {
@@ -295,12 +256,11 @@ 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 },
}); });
} }
log('downloaded hash:', hash);
setLocalHashInfo(hash, { setLocalHashInfo(hash, {
name, name,
description, description,
@@ -316,17 +276,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';
@@ -345,7 +305,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

@@ -12,7 +12,6 @@ export const defaultContext = {
markSuccess: noop, markSuccess: noop,
dismissError: noop, dismissError: noop,
downloadUpdate: noop, downloadUpdate: noop,
downloadAndInstallApk: noop,
currentHash: '', currentHash: '',
packageVersion: '', packageVersion: '',
}; };
@@ -24,7 +23,6 @@ export const PushyContext = createContext<{
markSuccess: () => void; markSuccess: () => void;
dismissError: () => void; dismissError: () => void;
downloadUpdate: () => void; downloadUpdate: () => void;
downloadAndInstallApk: (url: string) => void;
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

@@ -14,7 +14,7 @@ import {
} from 'react-native'; } from 'react-native';
import { Pushy } from './client'; import { Pushy } from './client';
import { currentVersion, isFirstTime, packageVersion } from './core'; import { currentVersion, isFirstTime, packageVersion } from './core';
import { CheckResult, ProgressData } from './type'; import { CheckResult } from './type';
import { PushyContext } from './context'; import { PushyContext } from './context';
export const PushyProvider = ({ export const PushyProvider = ({
@@ -24,23 +24,24 @@ export const PushyProvider = ({
client: Pushy; client: Pushy;
children: ReactNode; children: ReactNode;
}) => { }) => {
const { options } = client; const { strategy, useAlert } = client.options;
const stateListener = useRef<NativeEventSubscription>(); const stateListener = useRef<NativeEventSubscription>();
const [updateInfo, setUpdateInfo] = useState<CheckResult>(); const [updateInfo, setUpdateInfo] = useState<CheckResult>();
const [progress, setProgress] = useState<ProgressData>();
const [lastError, setLastError] = useState<Error>(); const [lastError, setLastError] = useState<Error>();
const dismissError = useCallback(() => { const dismissError = useCallback(() => {
setLastError(undefined); if (lastError) {
}, []); setLastError(undefined);
}
}, [lastError]);
const showAlert = useCallback( const showAlert = useCallback(
(...args: Parameters<typeof Alert.alert>) => { (...args: Parameters<typeof Alert.alert>) => {
if (options.useAlert) { if (useAlert) {
Alert.alert(...args); Alert.alert(...args);
} }
}, },
[options], [useAlert],
); );
const switchVersion = useCallback(() => { const switchVersion = useCallback(() => {
@@ -60,7 +61,7 @@ export const PushyProvider = ({
return; return;
} }
try { try {
const hash = await client.downloadUpdate(updateInfo, setProgress); const hash = await client.downloadUpdate(updateInfo);
if (!hash) { if (!hash) {
return; return;
} }
@@ -87,15 +88,6 @@ export const PushyProvider = ({
} }
}, [client, showAlert, updateInfo]); }, [client, showAlert, updateInfo]);
const downloadAndInstallApk = useCallback(
(downloadUrl: string) => {
if (Platform.OS === 'android' && downloadUrl) {
client.downloadAndInstallApk(downloadUrl, setProgress);
}
},
[client],
);
const checkUpdate = useCallback(async () => { const checkUpdate = useCallback(async () => {
let info: CheckResult; let info: CheckResult;
try { try {
@@ -114,7 +106,7 @@ export const PushyProvider = ({
onPress: () => { onPress: () => {
if (downloadUrl) { if (downloadUrl) {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) { if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl); client.downloadAndInstallApk(downloadUrl);
} else { } else {
Linking.openURL(downloadUrl); Linking.openURL(downloadUrl);
} }
@@ -138,13 +130,12 @@ export const PushyProvider = ({
], ],
); );
} }
}, [client, downloadAndInstallApk, downloadUpdate, showAlert]); }, [client, downloadUpdate, showAlert]);
const markSuccess = client.markSuccess; const markSuccess = client.markSuccess;
useEffect(() => { useEffect(() => {
const { strategy, dismissErrorAfter, autoMarkSuccess } = options; if (isFirstTime) {
if (isFirstTime && autoMarkSuccess) {
markSuccess(); markSuccess();
} }
if (strategy === 'both' || strategy === 'onAppResume') { if (strategy === 'both' || strategy === 'onAppResume') {
@@ -161,6 +152,7 @@ export const PushyProvider = ({
checkUpdate(); checkUpdate();
} }
let dismissErrorTimer: ReturnType<typeof setTimeout>; let dismissErrorTimer: ReturnType<typeof setTimeout>;
const { dismissErrorAfter } = client.options;
if (typeof dismissErrorAfter === 'number' && dismissErrorAfter > 0) { if (typeof dismissErrorAfter === 'number' && dismissErrorAfter > 0) {
dismissErrorTimer = setTimeout(() => { dismissErrorTimer = setTimeout(() => {
dismissError(); dismissError();
@@ -170,7 +162,7 @@ export const PushyProvider = ({
stateListener.current && stateListener.current.remove(); stateListener.current && stateListener.current.remove();
clearTimeout(dismissErrorTimer); clearTimeout(dismissErrorTimer);
}; };
}, [checkUpdate, options, dismissError, markSuccess]); }, [checkUpdate, client.options, dismissError, markSuccess, strategy]);
return ( return (
<PushyContext.Provider <PushyContext.Provider
@@ -186,8 +178,6 @@ export const PushyProvider = ({
downloadUpdate, downloadUpdate,
packageVersion, packageVersion,
currentHash: currentVersion, currentHash: currentVersion,
progress,
downloadAndInstallApk,
}} }}
> >
{children} {children}