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

Compare commits

...

84 Commits

Author SHA1 Message Date
sunnylqm
a6d4befca2 v10.7.1 2024-06-25 12:33:53 +08:00
sunnylqm
4fb0c691e6 v10.7.0 2024-06-25 12:26:18 +08:00
sunnylqm
b62e6d64cf v10.6.0 2024-06-11 12:25:45 +08:00
sunnylqm
9af0538a2a update example 2024-06-11 10:59:27 +08:00
sunnylqm
e63fa0fdb6 v10.6.0-beta.0 2024-06-11 10:44:18 +08:00
sunnylqm
6244bb9af2 v10.5.4 2024-04-23 09:31:16 +08:00
sunnylqm
9fd6293037 emptymodule 2024-04-23 00:24:32 +08:00
sunnylqm
e9e67b011c v10.5.3 2024-04-23 00:15:38 +08:00
sunnylqm
5996a7aa75 v10.5.2 2024-04-23 00:09:07 +08:00
sunnylqm
ad9b0778ba v10.5.1 2024-04-22 23:15:34 +08:00
sunnylqm
3e60cfd80f v10.5.0 2024-04-22 23:11:07 +08:00
sunnylqm
782b0e5227 v10.4.2 2024-04-22 09:57:53 +08:00
sunnylqm
d1ecfb3f93 v10.4.1 2024-04-18 22:50:20 +08:00
sunnylqm
571c2819b9 v10.4.0 2024-04-18 22:41:00 +08:00
sunnylqm
1f75688b92 Refactor assertRelease function 2024-04-18 22:39:03 +08:00
sunnylqm
de332c1796 Update PushyOptions strategy to allow null value 2024-04-02 21:21:15 +08:00
sunnylqm
80e0451983 v10.3.1 2024-03-21 22:11:38 +08:00
sunnylqm
b512ae18b7 do not show alert if no downloadurl 2024-03-21 22:11:09 +08:00
sunnylqm
fe75a2ca9e Remove blockUpdate method from UpdateContext and UpdateModule 2024-03-21 13:03:32 +08:00
sunnylqm
d84ad103fb v10.3.0 2024-03-20 21:50:18 +08:00
sunnylqm
208034fa7d fix module name 2024-03-20 21:49:44 +08:00
sunnylqm
c6430a9ed4 v10.2.9 2024-03-20 21:48:31 +08:00
sunnylqm
f2aec36705 remove blockupdate 2024-03-20 21:47:44 +08:00
sunnylqm
71e5b947d3 v10.2.8 2024-03-20 21:43:13 +08:00
sunnylqm
5dc8d8defc fix module name 2024-03-20 21:42:44 +08:00
sunnylqm
30687dddf2 v10.2.7 2024-03-20 21:38:51 +08:00
sunnylqm
57ddcc7758 fix codegenconfig 2024-03-20 21:37:59 +08:00
sunnylqm
a93bbe553d v10.3.0-beta.0 2024-03-20 20:54:48 +08:00
sunnylqm
356050d839 Add NativePushy module to the project 2024-03-20 20:42:31 +08:00
sunnylqm
5df3cb65b3 Merge branch 'master' of github.com:reactnativecn/react-native-pushy 2024-03-20 10:16:11 +08:00
sunnylqm
699eb0ea05 Update jsSrcsDir in package.json 2024-03-20 10:15:49 +08:00
Sunny Luo
36c4ff085c Create tea.yaml 2024-03-10 20:39:13 +08:00
sunnylqm
8c13dd69b1 v10.2.6 2024-03-08 16:05:08 +08:00
sunnylqm
2df04cb377 fix a wrong dep 2024-03-08 16:04:16 +08:00
sunnylqm
e39d4fa370 v10.2.5 2024-03-08 11:27:31 +08:00
sunnylqm
94cf96a0e5 chore: lint 2024-03-07 22:11:44 +08:00
sunnylqm
22c4b01ead v10.2.4 2024-03-07 18:10:16 +08:00
sunnylqm
f655a1d954 fix: avoid double check when init 2024-03-07 18:09:55 +08:00
sunnylqm
2bdc64ba1b v10.2.3 2024-03-07 17:58:30 +08:00
sunnylqm
f5242017b9 fix: ignore checkupdate in dev env 2024-03-07 17:58:03 +08:00
sunnylqm
42e2051290 fix: add timeout 2024-03-04 12:30:00 +08:00
sunnylqm
a66f354c3b v10.2.1 2024-03-03 08:50:19 +08:00
sunnylqm
592e13b77b return null if error 2024-03-03 08:49:46 +08:00
sunnylqm
2845a4302a v10.2.0 2024-03-02 12:25:11 +08:00
sunnylqm
84ef668102 feat: test urls 2024-03-02 12:24:41 +08:00
sunnylqm
c63e1501fe v10.1.3 2024-02-25 22:24:35 +08:00
sunnylqm
45bfa2560e feat: add getCurrentVersionInfo 2024-02-25 22:23:46 +08:00
sunnylqm
ab9c40bf2e v10.1.2 2024-02-25 00:05:14 +08:00
sunnylqm
d184beabaf fix: type 2024-02-25 00:04:55 +08:00
sunnylqm
68a6235145 v10.1.1 2024-02-25 00:03:58 +08:00
sunnylqm
a98a48d665 fix: type 2024-02-25 00:03:35 +08:00
sunnylqm
4bf004a274 v10.1.0 2024-02-24 11:37:41 +08:00
sunnylqm
f01716bcb2 feat: add logger 2024-02-24 11:36:58 +08:00
sunnylqm
4f9e1495c8 v10.0.2 2024-02-19 11:42:17 +08:00
sunnylqm
9c06bac91b fix: dead loop 2024-02-19 11:41:17 +08:00
sunnylqm
4923aff184 v10.0.1 2024-02-19 09:37:31 +08:00
sunnylqm
f6a38c1f48 fix: default strategy 2024-02-19 09:36:53 +08:00
Sunny Luo
92cfbb3fdf Merge pull request #426 from reactnativecn/v10
V10
2024-02-08 22:07:46 +08:00
sunnylqm
64ef8e129d fix: update example 2024-02-08 22:06:59 +08:00
sunnylqm
ce51b2ca81 v10.0.0-beta.3 2024-02-08 21:50:54 +08:00
sunnylqm
6c1662fce1 feat: add progress 2024-02-08 21:50:17 +08:00
sunnylqm
d9e4575964 fix example 2024-02-05 22:50:46 +08:00
sunnylqm
190103687c fix: options 2024-02-05 22:22:11 +08:00
sunnylqm
f6f055be64 update update.json 2024-02-05 22:09:53 +08:00
sunnylqm
05e5c5a1a7 v10.0.0-beta.2 2024-01-25 22:09:35 +08:00
sunnylqm
296498e20a update 2024-01-22 18:39:52 +08:00
sunnylqm
2a3b8e5707 feat: update example 2024-01-22 15:55:52 +08:00
sunnylqm
e86df57476 v10.0.0-beta.1 2024-01-22 15:34:54 +08:00
sunnylqm
40b2e9dea0 v10.0.0-beta.0 2024-01-22 15:06:02 +08:00
sunnylqm
1afc896306 feat: new version 2024-01-21 22:23:51 +08:00
sunnylqm
36533d43c4 fix: new version 2024-01-21 14:41:06 +08:00
sunnylqm
e5405b4977 translate 2024-01-18 00:32:21 +08:00
sunnylqm
9d93faab31 v10 2024-01-18 00:22:17 +08:00
sunnylqm
7229f8847a chore: indent 2023-12-31 17:05:37 +08:00
sunnylqm
1daafb0142 v9.1.6 2023-12-20 10:38:18 +08:00
sunnylqm
c1679a4cea fix: support gradle namespace 2023-12-20 10:37:43 +08:00
sunnylqm
7ab7dffb0f v9.1.5 2023-12-12 23:08:11 +08:00
sunnylqm
8622935bdf fix: zipslip 2023-12-12 23:07:11 +08:00
sunnylqm
b747b1f356 v9.1.4 2023-10-30 22:58:41 +08:00
sunnylqm
7752581470 chore: throttle switchversion 2023-10-30 22:58:09 +08:00
sunnylqm
33eb89d2a7 v9.1.3 2023-10-28 18:28:54 +08:00
sunnylqm
d111bf5a9c chore: rename onPushyEvents 2023-10-28 18:28:23 +08:00
sunnylqm
23346a5f1d v9.1.2 2023-10-28 17:26:19 +08:00
sunnylqm
5aca2104c2 fix: simpleUpdate for web 2023-10-28 17:25:54 +08:00
48 changed files with 8507 additions and 3784 deletions

View File

@@ -1,29 +0,0 @@
{
"extends": "eslint-config-airbnb/base",
"parser": "babel-eslint",
"env": {
"browser": true,
"node": true,
"mocha": true
},
"rules": {
// Disable for console/alert
"no-console": 0,
"no-alert": 0,
"indent": [2, 2, {"SwitchCase": 1}]
},
"plugins": [
"import"
],
"settings": {
"import/parser": "babel-eslint",
"import/resolve": {
"moduleDirectory": ["node_modules", "src"]
}
},
"globals": {
"__DEV__": true,
"__OPTION__": true
}
}

4
.eslintrc.js Normal file
View File

@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: '@react-native',
};

View File

@@ -41,14 +41,17 @@ export const testFunctionDefaultRegion = functions.https.onCall(data => {
const { type, asError, inputData } = data;
if (!Object.hasOwnProperty.call(SAMPLE_DATA, type)) {
throw new functions.https.HttpsError('invalid-argument', 'Invalid test requested.');
throw new functions.https.HttpsError(
'invalid-argument',
'Invalid test requested.',
);
}
const outputData = SAMPLE_DATA[type];
try {
assert.deepEqual(outputData, inputData);
} catch (e) {
} catch (e: any) {
console.error(e);
throw new functions.https.HttpsError(
'invalid-argument',

View File

@@ -47,4 +47,6 @@ Example
yarn.lock
domains.json
endpoints.json
endpoints.json
tea.yaml

View File

@@ -1,4 +1,6 @@
module.exports = {
trailingComma: 'all',
arrowParens: 'avoid',
bracketSameLine: true,
singleQuote: true,
trailingComma: 'all',
};

View File

@@ -1,3 +1,8 @@
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
env: {
production: {
plugins: ['react-native-paper/babel'],
},
},
};

View File

@@ -28,14 +28,7 @@ describe('测试Native模块的方法', () => {
await element(by.id('done')).longPress();
await expect(element(by.id('done'))).toBeNotVisible();
});
it('setBlockUpdate', async () => {
await element(by.id('setBlockUpdate')).longPress();
await element(by.id('submit')).longPress();
await expect(element(by.text('done'))).toBeVisible();
await element(by.id('done')).longPress();
await expect(element(by.id('done'))).toBeNotVisible();
});
if (device.getPlatform() === 'android') {
it('reloadUpdate', async () => {
await element(by.id('reloadUpdate')).longPress();

View File

@@ -284,17 +284,19 @@ PODS:
- React-jsinspector (0.69.8)
- React-logger (0.69.8):
- glog
- react-native-update (9.0.0):
- react-native-safe-area-context (4.8.2):
- React-Core
- react-native-update (10.0.0-beta.1):
- React
- React-Core
- react-native-update/HDiffPatch (= 9.0.0)
- react-native-update/RCTPushy (= 9.0.0)
- react-native-update/HDiffPatch (= 10.0.0-beta.1)
- react-native-update/RCTPushy (= 10.0.0-beta.1)
- SSZipArchive
- react-native-update/HDiffPatch (9.0.0):
- react-native-update/HDiffPatch (10.0.0-beta.1):
- React
- React-Core
- SSZipArchive
- react-native-update/RCTPushy (9.0.0):
- react-native-update/RCTPushy (10.0.0-beta.1):
- React
- React-Core
- SSZipArchive
@@ -364,6 +366,8 @@ PODS:
- React-jsi (= 0.69.8)
- React-logger (= 0.69.8)
- React-perflogger (= 0.69.8)
- RNVectorIcons (10.0.3):
- React-Core
- SocketRocket (0.6.0)
- SSZipArchive (2.4.3)
- Yoga (1.14.0)
@@ -414,6 +418,7 @@ DEPENDENCIES:
- React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`)
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
- React-logger (from `../node_modules/react-native/ReactCommon/logger`)
- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)
- react-native-update (from `../node_modules/react-native-update`)
- React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`)
- React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`)
@@ -427,6 +432,7 @@ DEPENDENCIES:
- React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`)
- React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`)
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- RNVectorIcons (from `../node_modules/react-native-vector-icons`)
- Yoga (from `../node_modules/react-native/ReactCommon/yoga`)
SPEC REPOS:
@@ -487,6 +493,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon/jsinspector"
React-logger:
:path: "../node_modules/react-native/ReactCommon/logger"
react-native-safe-area-context:
:path: "../node_modules/react-native-safe-area-context"
react-native-update:
:path: "../node_modules/react-native-update"
React-perflogger:
@@ -513,6 +521,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon/runtimeexecutor"
ReactCommon:
:path: "../node_modules/react-native/ReactCommon"
RNVectorIcons:
:path: "../node_modules/react-native-vector-icons"
Yoga:
:path: "../node_modules/react-native/ReactCommon/yoga"
@@ -549,7 +559,8 @@ SPEC CHECKSUMS:
React-jsiexecutor: 2cf8ea3753afb81dfcc386613dbbb0b5d155fb34
React-jsinspector: 0eda09e9cf22bbb5dbb1d23143b03a31acf37d67
React-logger: 5997ab008583826c10ffe4e1ff990363e975639d
react-native-update: 2b5ef06bfeaa668614c8deb7ec4d20dcf56f9278
react-native-safe-area-context: 0ee144a6170530ccc37a0fd9388e28d06f516a89
react-native-update: 767449a2cf592387b9aecb97980ec0536d72c890
React-perflogger: ad1416a715d86b32f456e5d0aed99c3b52f1de37
React-RCTActionSheet: cbf7c6a953982562418ee72a1084ff7b9447b558
React-RCTAnimation: 33df3e25824dd7313edec28dded2745542f9352b
@@ -562,6 +573,7 @@ SPEC CHECKSUMS:
React-RCTVibration: 5462287ee85304ba1a00474665ab292e63a41663
React-runtimeexecutor: 9df680f18497367bcf5c15b6b6406c0f2dfa2b6a
ReactCommon: c10f046f3ef8561e7c8e7e9b9dae2ecc9ffc48ef
RNVectorIcons: bc7ee28cadf39c77a49232a14738dfce690f66cd
SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608
SSZipArchive: fe6a26b2a54d5a0890f2567b5cc6de5caa600aef
Yoga: d3820731e0ca3a4933f061ad29defaf7726e3251
@@ -569,4 +581,4 @@ SPEC CHECKSUMS:
PODFILE CHECKSUM: 618d17df10f335f1d113daac849a7997894646b2
COCOAPODS: 1.11.3
COCOAPODS: 1.14.3

View File

@@ -1,12 +1,12 @@
const path = require('path');
const extraNodeModules = {
react: path.resolve(__dirname, 'node_modules/react'),
'react-native': path.resolve(__dirname, 'node_modules/react-native'),
'react-native-update': path.resolve(__dirname, '../..'),
'@babel/runtime': path.resolve(__dirname, 'node_modules/@babel/runtime'),
};
const watchFolders = [path.resolve(__dirname, '../..')];
// const extraNodeModules = {
// react: path.resolve(__dirname, 'node_modules/react'),
// 'react-native': path.resolve(__dirname, 'node_modules/react-native'),
// 'react-native-update': path.resolve(__dirname, '../..'),
// '@babel/runtime': path.resolve(__dirname, 'node_modules/@babel/runtime'),
// };
// const watchFolders = [path.resolve(__dirname, '../..')];
module.exports = {
transformer: {
@@ -17,8 +17,8 @@ module.exports = {
},
}),
},
resolver: {
extraNodeModules,
},
watchFolders,
// resolver: {
// extraNodeModules,
// },
// watchFolders,
};

View File

@@ -16,7 +16,10 @@
"postinstall-postinstall": "^2.1.0",
"react": "18.0.0",
"react-native": "0.69.8",
"react-native-update": "link:../.."
"react-native-paper": "^5.12.1",
"react-native-safe-area-context": "^4.8.2",
"react-native-update": "^10.6.0-beta.0",
"react-native-vector-icons": "^10.0.3"
},
"devDependencies": {
"@babel/core": "^7.21.0",

View File

@@ -19,23 +19,25 @@ const UUID = '00000000-0000-0000-0000-000000000000';
const DownloadUrl =
'http://cos.pgyer.com/697913e94d7441f20c686e2b0996a1aa.apk?sign=7a8f11b1df82cba45c8ac30b1acec88c&t=1680404102&response-content-disposition=attachment%3Bfilename%3DtestHotupdate_1.0.apk';
const CustomDialog = ({title, visible, onConfirm}) => {
if (!visible) {
return null;
}
const CustomDialog = ({title, visible, onConfirm}) => {
if (!visible) {
return null;
}
return (
<View style={styles.overlay}>
<View style={styles.dialog}>
<Text style={styles.title}>{title}</Text>
<TouchableOpacity testID='done' style={styles.button} onLongPress={onConfirm}>
<Text style={styles.buttonText}>确认</Text>
</TouchableOpacity>
</View>
return (
<View style={styles.overlay}>
<View style={styles.dialog}>
<Text style={styles.title}>{title}</Text>
<TouchableOpacity
testID="done"
style={styles.button}
onLongPress={onConfirm}>
<Text style={styles.buttonText}>确认</Text>
</TouchableOpacity>
</View>
);
};
</View>
);
};
export default function TestConsole({visible}) {
const [text, setText] = useState('');
const [running, setRunning] = useState(false);
@@ -64,13 +66,6 @@ export default function TestConsole({visible}) {
setText(`setUuid\n${UUID}`);
},
},
{
name: 'setBlockUpdate',
invoke: () => {
setText('setBlockUpdate');
setOptions({reason: 'application has been block', until: 1673082950});
},
},
{
name: 'reloadUpdate',
invoke: () => {
@@ -132,9 +127,8 @@ export default function TestConsole({visible}) {
testID={NativeTestMethod[i].name}
onLongPress={() => {
NativeTestMethod[i].invoke();
}}
>
<Text>{NativeTestMethod[i].name}</Text>
}}>
<Text>{NativeTestMethod[i].name}</Text>
</TouchableOpacity>,
);
}
@@ -164,8 +158,14 @@ export default function TestConsole({visible}) {
/>
{running && <ActivityIndicator />}
<TouchableOpacity
style={{backgroundColor:'rgb(0,140,237)', justifyContent: 'center',
alignItems: 'center',paddingTop:10,paddingBottom:10,marginBottom:5}}
style={{
backgroundColor: 'rgb(0,140,237)',
justifyContent: 'center',
alignItems: 'center',
paddingTop: 10,
paddingBottom: 10,
marginBottom: 5,
}}
testID="submit"
onLongPress={async () => {
setRunning(true);
@@ -195,17 +195,18 @@ export default function TestConsole({visible}) {
setAlertMsg(e.message);
}
setRunning(false);
}}
>
<Text style={{color:'white'}}>执行</Text>
}}>
<Text style={{color: 'white'}}>执行</Text>
</TouchableOpacity>
<Button title="重置" onPress={() => setText('')} />
{renderTestView()}
<CustomDialog
title={alertMsg}
visible={alertVisible}
onConfirm={()=>{setAlertVisible(false)}}
/>
<Button title="重置" onPress={() => setText('')} />
{renderTestView()}
<CustomDialog
title={alertMsg}
visible={alertVisible}
onConfirm={() => {
setAlertVisible(false);
}}
/>
</SafeAreaView>
</Modal>
);

View File

@@ -1,206 +0,0 @@
import React, {Component} from 'react';
import {
StyleSheet,
Platform,
Text,
View,
Alert,
TouchableOpacity,
Linking,
Image,
} from 'react-native';
import {
isFirstTime,
isRolledBack,
packageVersion,
currentVersion,
checkUpdate,
downloadUpdate,
switchVersion,
switchVersionLater,
markSuccess,
downloadAndInstallApk,
cInfo,
} from 'react-native-update';
import TestConsole from './TestConsole';
import _updateConfig from '../update.json';
const {appKey} = _updateConfig[Platform.OS];
export default class App extends Component {
state = {
received: 0,
total: 0,
showTestConsole: false,
};
componentDidMount() {
if (isRolledBack) {
Alert.alert('提示', '刚刚更新失败了,版本被回滚.');
} else if (isFirstTime) {
Alert.alert(
'提示',
'这是当前版本第一次启动,是否要模拟启动失败?将回滚到上一版本',
[
{
text: '是',
onPress: () => {
throw new Error('模拟启动失败,请重启应用');
},
},
{
text: '否',
onPress: () => {
markSuccess();
},
},
],
);
}
}
doUpdate = async info => {
try {
const hash = await downloadUpdate(info, {
onDownloadProgress: ({received, total}) => {
this.setState({
received,
total,
});
},
});
if (!hash) {
return;
}
Alert.alert('提示', '下载完毕,是否重启应用?', [
{
text: '是',
onPress: () => {
switchVersion(hash);
},
},
{text: '否'},
{
text: '下次启动时',
onPress: () => {
switchVersionLater(hash);
},
},
]);
} catch (err) {
Alert.alert('更新失败', err.message);
}
};
checkUpdate = async () => {
let info;
try {
info = await checkUpdate(appKey);
} catch (err) {
Alert.alert('更新检查失败', err.message);
return;
}
if (info.expired) {
Alert.alert('提示', '您的应用版本已更新,点击确定下载安装新版本', [
{
text: '确定',
onPress: () => {
if (info.downloadUrl) {
// apk可直接下载安装
if (
Platform.OS === 'android' &&
info.downloadUrl.endsWith('.apk')
) {
downloadAndInstallApk({
url: info.downloadUrl,
onDownloadProgress: ({received, total}) => {
this.setState({
received,
total,
});
},
});
} else {
Linking.openURL(info.downloadUrl);
}
}
},
},
]);
} else if (info.upToDate) {
Alert.alert('提示', '您的应用版本已是最新.');
} else {
Alert.alert(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
[
{
text: '是',
onPress: () => {
this.doUpdate(info);
},
},
{text: '否'},
],
);
}
};
render() {
const {received, total, showTestConsole} = this.state;
return (
<View style={styles.container}>
<Text style={styles.welcome}>欢迎使用热更新服务</Text>
<Image
resizeMode={'contain'}
source={require('./assets/shezhi.png')}
style={styles.image}
/>
<Text style={styles.instructions}>
这是版本一 {'\n'}
当前原生包版本号: {packageVersion}
{'\n'}
当前热更新版本Hash: {currentVersion || '(空)'}
{'\n'}
</Text>
<Text>
下载进度{received} / {total}
</Text>
<TouchableOpacity onPress={this.checkUpdate}>
<Text style={styles.instructions}>点击这里检查更新</Text>
</TouchableOpacity>
<TouchableOpacity
testID="testcase"
style={{marginTop: 15}}
onLongPress={() => {
this.setState({showTestConsole: true});
}}>
<Text style={styles.instructions}>
react-native-update版本{cInfo.pushy}
</Text>
</TouchableOpacity>
<TestConsole visible={showTestConsole} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
image: {},
});

View File

@@ -0,0 +1,166 @@
import React, {useState} from 'react';
import {
StyleSheet,
Platform,
Text,
View,
TouchableOpacity,
Image,
Switch,
} from 'react-native';
import {Icon, PaperProvider, Snackbar, Banner} from 'react-native-paper';
import TestConsole from './TestConsole';
import _updateConfig from '../update.json';
import {PushyProvider, Pushy, usePushy} from 'react-native-update';
const {appKey} = _updateConfig[Platform.OS];
function App() {
const {
client,
checkUpdate,
downloadUpdate,
switchVersionLater,
switchVersion,
updateInfo,
packageVersion,
currentHash,
progress: {received, total} = {},
} = usePushy();
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
const [showTestConsole, setShowTestConsole] = useState(false);
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
const snackbarVisible =
!useDefaultAlert && showUpdateSnackbar && updateInfo?.update;
return (
<View style={styles.container}>
<Text style={styles.welcome}>使Pushy热更新服务</Text>
<View style={{flexDirection: 'row'}}>
<Text>
{useDefaultAlert ? '当前使用' : '当前不使用'}alert更新提示
</Text>
<Switch
value={useDefaultAlert}
onValueChange={v => {
setUseDefaultAlert(v);
client?.setOptions({
updateStrategy: v ? null : 'alwaysAlert',
});
setShowUpdateSnackbar(!v);
}}
/>
</View>
<Image
resizeMode={'contain'}
source={require('./assets/shezhi.png')}
style={styles.image}
/>
<Text style={styles.instructions}>
{'\n'}
: {packageVersion}
{'\n'}
Hash: {currentHash || '(空)'}
{'\n'}
</Text>
<Text>
{received} / {total}
</Text>
<TouchableOpacity
onPress={() => {
checkUpdate();
setShowUpdateSnackbar(true);
}}>
<Text style={styles.instructions}></Text>
</TouchableOpacity>
<TouchableOpacity
testID="testcase"
style={{marginTop: 15}}
onLongPress={() => {
setShowTestConsole(true);
}}>
<Text style={styles.instructions}>
react-native-update版本{client?.version}
</Text>
</TouchableOpacity>
<TestConsole visible={showTestConsole} />
{snackbarVisible && (
<Snackbar
visible={snackbarVisible}
onDismiss={() => {
setShowUpdateSnackbar(false);
}}
action={{
label: '更新',
onPress: async () => {
setShowUpdateSnackbar(false);
await downloadUpdate();
setShowUpdateBanner(true);
},
}}>
<Text style={{color: 'white'}}>
({updateInfo.name})
</Text>
</Snackbar>
)}
<Banner
style={{width: '100%', position: 'absolute', top: 0}}
visible={showUpdateBanner}
actions={[
{
label: '立即重启',
onPress: switchVersion,
},
{
label: '下次再说',
onPress: () => {
switchVersionLater();
setShowUpdateBanner(false);
},
},
]}
icon={({size}) => (
<Icon name="checkcircleo" size={size} color="#00f" />
)}>
</Banner>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
image: {},
});
const pushyClient = new Pushy({
appKey,
});
export default function Root() {
return (
<PushyProvider client={pushyClient}>
<PaperProvider>
<App />
</PaperProvider>
</PushyProvider>
);
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,19 @@ def isNewArchitectureEnabled() {
return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}
def supportsNamespace() {
def parsed = com.android.Version.ANDROID_GRADLE_PLUGIN_VERSION.tokenize('.')
def major = parsed[0].toInteger()
def minor = parsed[1].toInteger()
// Namespace support was added in 7.3.0
if (major == 7 && minor >= 3) {
return true
}
return major >= 8
}
apply plugin: 'com.android.library'
if (isNewArchitectureEnabled()) {
apply plugin: 'com.facebook.react'
@@ -16,6 +29,16 @@ if (isNewArchitectureEnabled()) {
android {
if (supportsNamespace()) {
namespace "cn.reactnative.modules.update"
sourceSets {
main {
manifest.srcFile "src/main/AndroidManifestNew.xml"
}
}
}
compileSdkVersion safeExtGet('compileSdkVersion', 28)
buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3')

View File

@@ -1,4 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.reactnative.modules.update">
<application>

View File

@@ -0,0 +1,14 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<meta-data android:name="pushy_build_time" android:value="@string/pushy_build_time" />
<provider
android:name=".PushyFileProvider"
android:authorities="${applicationId}.pushy.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/pushy_file_paths" />
</provider>
</application>
</manifest>

View File

@@ -237,19 +237,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
while (entries.hasMoreElements()) {
ZipEntry ze = entries.nextElement();
String fn = ze.getName();
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();
@@ -324,8 +312,15 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
} else {
target = copyList.get((from));
}
target.add(new File(param.unzipDirectory, to));
//copyFromResource(from, new File(param.unzipDirectory, to));
File toFile = new File(param.unzipDirectory, to);
// Fixing a Zip Path Traversal Vulnerability
// https://support.google.com/faqs/answer/9294009
String canonicalPath = toFile.getCanonicalPath();
if (!canonicalPath.startsWith(param.unzipDirectory.getCanonicalPath() + File.separator)) {
throw new SecurityException("Illegal name: " + to);
}
target.add(toFile);
}
continue;
}
@@ -339,18 +334,9 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
fout.close();
continue;
}
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();
@@ -419,18 +405,8 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
fout.close();
continue;
}
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();

View File

@@ -1,5 +1,7 @@
package cn.reactnative.modules.update;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -10,12 +12,15 @@ import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class SafeZipFile extends ZipFile {
public SafeZipFile(File file) throws IOException {
super(file);
}
private static final int BUFFER_SIZE = 8192;
@Override
public Enumeration<? extends ZipEntry> entries() {
return new SafeZipEntryIterator(super.entries());
@@ -43,40 +48,46 @@ public class SafeZipFile extends ZipFile {
* avoid ZipperDown
*/
if (null != name && (name.contains("../") || name.contains("..\\"))) {
throw new SecurityException("illegal entry: " + entry.getName());
throw new SecurityException("illegal entry: " + name);
}
}
return entry;
}
}
public void unzipToFile(ZipEntry entry, File output) throws IOException {
InputStream inputStream = null;
try {
inputStream = getInputStream(entry);
writeOutInputStream(output, inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
public void unzipToPath(ZipEntry ze, File targetPath) throws IOException {
String name = ze.getName();
File target = new File(targetPath, name);
// Fixing a Zip Path Traversal Vulnerability
// https://support.google.com/faqs/answer/9294009
String canonicalPath = target.getCanonicalPath();
if (!canonicalPath.startsWith(targetPath.getCanonicalPath() + File.separator)) {
throw new SecurityException("Illegal name: " + name);
}
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + name);
}
if (ze.isDirectory()) {
target.mkdirs();
return;
}
unzipToFile(ze, target);
}
public void unzipToFile(ZipEntry ze, File target) throws IOException {
try (InputStream inputStream = getInputStream(ze)) {
try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(target));
BufferedInputStream input = new BufferedInputStream(inputStream)) {
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = input.read(buffer, 0, BUFFER_SIZE)) >= 0) {
output.write(buffer, 0, n);
}
}
}
}
private void writeOutInputStream(File file, InputStream inputStream) throws IOException {
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(
new FileOutputStream(file));
BufferedInputStream input = new BufferedInputStream(inputStream);
byte b[] = new byte[8192];
int n;
while ((n = input.read(b, 0, 8192)) >= 0) {
output.write(b, 0, n);
}
} finally {
if (output != null) {
output.close();
}
}
}
}

View File

@@ -69,13 +69,6 @@ public class UpdateContext {
return context.getString(R.string.pushy_build_time);
}
public Map getBlockUpdate() {
return new HashMap<String, Object>() {{
put("until", sp.getInt("blockUntil", 0));
put("reason", sp.getString("blockReason", null));
}};
}
public boolean getIsUsingBundleUrl() {
return isUsingBundleUrl;
}
@@ -166,13 +159,6 @@ public class UpdateContext {
return sp.getString(key, null);
}
public void setBlockUpdate(int until, String reason) {
SharedPreferences.Editor editor = sp.edit();
editor.putInt("blockUntil", until);
editor.putString("blockReason", reason);
editor.apply();
}
public String getCurrentVersion() {
return sp.getString("currentVersion", null);
}

View File

@@ -192,23 +192,6 @@ public class UpdateModuleImpl {
}
}
public static void setBlockUpdate(UpdateContext updateContext, ReadableMap options,Promise promise) {
try {
final int until = options.getInt("until");
final String reason = options.getString("reason");
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setBlockUpdate(until, reason);
}
});
promise.resolve(true);
}catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
}
public static void setUuid(UpdateContext updateContext, String uuid, Promise promise) {
try {
UiThreadUtil.runOnUiThread(new Runnable() {

View File

@@ -14,7 +14,7 @@ import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class UpdateModule extends NativeUpdateSpec {
public class UpdateModule extends NativePushySpec {
UpdateContext updateContext;
public static ReactApplicationContext mContext;
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
@@ -45,7 +45,6 @@ public class UpdateModule extends NativeUpdateSpec {
if (rolledBackVersion != null) {
updateContext.clearRollbackMark();
}
constants.put("blockUpdate", updateContext.getBlockUpdate());
constants.put("uuid", updateContext.getKv("uuid"));
return constants;
}
@@ -57,7 +56,7 @@ public class UpdateModule extends NativeUpdateSpec {
@Override
public void downloadFullUpdate(ReadableMap options, final Promise promise) {
UpdateModuleImpl.downloadFullUpdate(this.updateContext,options,promise);
UpdateModuleImpl.downloadFullUpdate(this.updateContext,options,promise);
}
@Override
@@ -108,11 +107,6 @@ public class UpdateModule extends NativeUpdateSpec {
UpdateModuleImpl.markSuccess(updateContext,promise);
}
@Override
public void setBlockUpdate(ReadableMap options,Promise promise) {
UpdateModuleImpl.setBlockUpdate(updateContext,options,promise);
}
@Override
public void setUuid(final String uuid, Promise promise) {
UpdateModuleImpl.setUuid(updateContext,uuid,promise);

View File

@@ -59,7 +59,6 @@ public class UpdateModule extends ReactContextBaseJavaModule {
if (rolledBackVersion != null) {
updateContext.clearRollbackMark();
}
constants.put("blockUpdate", updateContext.getBlockUpdate());
constants.put("uuid", updateContext.getKv("uuid"));
return constants;
}
@@ -239,18 +238,6 @@ public class UpdateModule extends ReactContextBaseJavaModule {
});
}
@ReactMethod
public void setBlockUpdate(ReadableMap options) {
final int until = options.getInt("until");
final String reason = options.getString("reason");
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setBlockUpdate(until, reason);
}
});
}
@ReactMethod
public void setUuid(final String uuid) {
UiThreadUtil.runOnUiThread(new Runnable() {

3
babel.config.js Normal file
View File

@@ -0,0 +1,3 @@
module.exports = {
presets: ['module:@react-native/babel-preset'],
};

View File

@@ -16,7 +16,6 @@ static NSString *const paramLastVersion = @"lastVersion";
static NSString *const paramCurrentVersion = @"currentVersion";
static NSString *const paramIsFirstTime = @"isFirstTime";
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
static NSString *const keyBlockUpdate = @"REACTNATIVECN_PUSHY_BLOCKUPDATE";
static NSString *const keyUuid = @"REACTNATIVECN_PUSHY_UUID";
static NSString *const keyHashInfo = @"REACTNATIVECN_PUSHY_HASH_";
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
@@ -157,7 +156,6 @@ RCT_EXPORT_MODULE(RCTPushy);
ret[@"buildTime"] = [RCTPushy buildTime];
ret[@"rolledBackVersion"] = [defaults objectForKey:keyRolledBackMarked];
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
ret[@"blockUpdate"] = [defaults objectForKey:keyBlockUpdate];
ret[@"uuid"] = [defaults objectForKey:keyUuid];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
@@ -192,24 +190,6 @@ RCT_EXPORT_MODULE(RCTPushy);
return self;
}
RCT_EXPORT_METHOD(setBlockUpdate:(NSDictionary *)options
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
// NSMutableDictionary *blockUpdateInfo = [NSMutableDictionary new];
// blockUpdateInfo[@"reason"] = options[@"reason"];
// blockUpdateInfo[@"until"] = options[@"until"];
@try {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:options forKey:keyBlockUpdate];
[defaults synchronize];
resolve(@true);
}
@catch (NSException *exception) {
reject(@"执行报错", nil, nil);
}
}
RCT_EXPORT_METHOD(setUuid:(NSString *)uuid resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{

View File

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

View File

@@ -1,2 +0,0 @@
export * from './main';
export * from './simpleUpdate';

View File

@@ -1,18 +0,0 @@
export const downloadRootDir = '';
export const packageVersion = '';
export const currentVersion = '';
export const isFirstTime = false;
export const isRolledBack = false;
const noop = () => {};
export const checkUpdate = noop;
export const downloadUpdate = noop;
export const switchVersion = noop;
export const switchVersionLater = noop;
export const markSuccess = noop;
export const downloadAndInstallApk = noop;
export const setCustomEndpoints = noop;
export const getCurrentVersionInfo = noop;
export const simpleUpdate = noop;
export const onEvents = noop;

View File

@@ -1,396 +0,0 @@
import {
updateBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
} from './endpoint';
import {
NativeEventEmitter,
NativeModules,
Platform,
PermissionsAndroid,
} from 'react-native';
import {
CheckResult,
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
import { assertRelease, logger } from './utils';
export { setCustomEndpoints };
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
const isTurboModuleEnabled = global.__turboModuleProxy != null;
export const PushyModule = isTurboModuleEnabled
? require('./NativeUpdate').default
: NativeModules.Pushy;
if (!PushyModule) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
}
const PushyConstants = isTurboModuleEnabled
? PushyModule.getConstants()
: PushyModule;
export const downloadRootDir = PushyConstants.downloadRootDir;
export const packageVersion = PushyConstants.packageVersion;
export const currentVersion = PushyConstants.currentVersion;
export const isFirstTime = PushyConstants.isFirstTime;
const rolledBackVersion = PushyConstants.rolledBackVersion;
export const isRolledBack = typeof rolledBackVersion === 'string';
export const buildTime = PushyConstants.buildTime;
let blockUpdate = PushyConstants.blockUpdate;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
}
export async function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;
metaInfo?: string;
}> {
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
}
const eventEmitter = new NativeEventEmitter(PushyModule);
if (!uuid) {
uuid = require('nanoid/non-secure').nanoid();
PushyModule.setUuid(uuid);
}
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,
message,
...data,
},
});
}
logger('uuid: ' + uuid);
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,
};
let lastChecking;
const empty = {};
let lastResult: CheckResult;
export async function checkUpdate(APPKEY: string) {
assertRelease();
const now = Date.now();
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
// logger('repeated checking, ignored');
return lastResult;
}
lastChecking = now;
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
report({
type: 'errorChecking',
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"之后重试。`,
});
return lastResult || empty;
}
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;
try {
resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
} catch (e) {
report({
type: 'errorChecking',
message: '无法连接主更新服务器,尝试备用节点',
});
const backupEndpoints = await updateBackupEndpoints();
if (backupEndpoints) {
try {
resp = await Promise.race(
backupEndpoints.map((endpoint) =>
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
),
);
} catch {}
}
}
if (!resp) {
report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
return lastResult || empty;
}
const result: CheckResult = await resp.json();
lastResult = result;
// @ts-ignore
checkOperation(result.op);
if (resp.status !== 200) {
report({
type: 'errorChecking',
//@ts-ignore
message: result.message,
});
}
return result;
}
function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) {
return;
}
op.forEach((action) => {
if (action.type === 'block') {
blockUpdate = {
reason: action.reason,
until: Math.round((Date.now() + action.duration) / 1000),
};
PushyModule.setBlockUpdate(blockUpdate);
}
});
}
let downloadingThrottling = false;
let downloadedHash: string;
export async function downloadUpdate(
options: UpdateAvailableResult,
eventListeners?: {
onDownloadProgress?: (data: ProgressData) => void;
},
) {
assertRelease();
if (!options.update) {
return;
}
if (rolledBackVersion === options.hash) {
logger(`rolledback hash ${rolledBackVersion}, ignored`);
return;
}
if (downloadedHash === options.hash) {
logger(`duplicated downloaded hash ${downloadedHash}, ignored`);
return downloadedHash;
}
if (downloadingThrottling) {
logger('repeated downloading, ignored');
return;
}
downloadingThrottling = true;
setTimeout(() => {
downloadingThrottling = false;
}, 3000);
let progressHandler;
if (eventListeners) {
if (eventListeners.onDownloadProgress) {
const downloadCallback = eventListeners.onDownloadProgress;
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
if (progressData.hash === options.hash) {
downloadCallback(progressData);
}
},
);
}
}
let succeeded = false;
report({ type: 'downloading' });
if (options.diffUrl) {
logger('downloading diff');
try {
await PushyModule.downloadPatchFromPpk({
updateUrl: options.diffUrl,
hash: options.hash,
originHash: currentVersion,
});
succeeded = true;
} catch (e) {
logger(`diff error: ${e.message}, try pdiff`);
}
}
if (!succeeded && options.pdiffUrl) {
logger('downloading pdiff');
try {
await PushyModule.downloadPatchFromPackage({
updateUrl: options.pdiffUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`pdiff error: ${e.message}, try full patch`);
}
}
if (!succeeded && options.updateUrl) {
logger('downloading full patch');
try {
await PushyModule.downloadFullUpdate({
updateUrl: options.updateUrl,
hash: options.hash,
});
succeeded = true;
} catch (e) {
logger(`full patch error: ${e.message}`);
}
}
progressHandler && progressHandler.remove();
if (!succeeded) {
return report({ type: 'errorUpdate', data: { newVersion: options.hash } });
}
setLocalHashInfo(options.hash, {
name: options.name,
description: options.description,
metaInfo: options.metaInfo,
});
downloadedHash = options.hash;
return options.hash;
}
function assertHash(hash: string) {
if (!downloadedHash) {
logger(`no downloaded hash`);
return;
}
if (hash !== downloadedHash) {
logger(`use downloaded hash ${downloadedHash} first`);
return;
}
return true;
}
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
PushyModule.reloadUpdate({ hash });
}
}
export function switchVersionLater(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
PushyModule.setNeedUpdate({ hash });
}
}
let marked = false;
export function markSuccess() {
assertRelease();
if (marked) {
logger('repeated markSuccess, ignored');
return;
}
marked = true;
PushyModule.markSuccess();
report({ type: 'markSuccess' });
}
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 report({ type: 'rejectStoragePermission' });
}
} catch (err) {
return report({ type: 'errorStoragePermission' });
}
}
let hash = Date.now().toString();
let progressHandler;
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData: ProgressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
await PushyModule.downloadAndInstallApk({
url,
target: 'update.apk',
hash,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
});
progressHandler && progressHandler.remove();
}

View File

@@ -1,135 +0,0 @@
import React, { PureComponent, ComponentType } from 'react';
import {
Platform,
Alert,
Linking,
AppState,
NativeEventSubscription,
} from 'react-native';
import {
isFirstTime,
isRolledBack,
checkUpdate,
downloadUpdate,
switchVersion,
switchVersionLater,
markSuccess,
downloadAndInstallApk,
onEvents,
} from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(
WrappedComponent: ComponentType,
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);
}
return __DEV__
? WrappedComponent
: class AppUpdate extends PureComponent {
stateListener: NativeEventSubscription;
componentDidMount() {
if (isRolledBack) {
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
} else if (isFirstTime) {
markSuccess();
}
this.stateListener = AppState.addEventListener(
'change',
(nextAppState) => {
if (nextAppState === 'active') {
this.checkUpdate();
}
},
);
this.checkUpdate();
}
componentWillUnmount() {
this.stateListener && this.stateListener.remove();
}
doUpdate = async (info) => {
try {
const hash = await downloadUpdate(info);
if (!hash) {
return;
}
this.stateListener && this.stateListener.remove();
Alert.alert('提示', '下载完毕,是否立即更新?', [
{
text: '以后再说',
style: 'cancel',
onPress: () => {
switchVersionLater(hash);
},
},
{
text: '立即更新',
style: 'default',
onPress: () => {
switchVersion(hash);
},
},
]);
} catch (err) {
Alert.alert('更新失败', err.message);
}
};
checkUpdate = async () => {
let info;
try {
info = await checkUpdate(appKey!);
} catch (err) {
Alert.alert('更新检查失败', err.message);
return;
}
if (info.expired) {
Alert.alert('提示', '您的应用版本已更新,点击确定下载安装新版本', [
{
text: '确定',
onPress: () => {
if (info.downloadUrl) {
if (
Platform.OS === 'android' &&
info.downloadUrl.endsWith('.apk')
) {
downloadAndInstallApk({
url: info.downloadUrl,
});
} else {
Linking.openURL(info.downloadUrl);
}
}
},
},
]);
} else if (info.update) {
Alert.alert(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
[
{ text: '否', style: 'cancel' },
{
text: '是',
style: 'default',
onPress: () => {
this.doUpdate(info);
},
},
],
);
}
};
render() {
return <WrappedComponent {...this.props} />;
}
};
}

View File

@@ -1,71 +0,0 @@
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,9 +0,0 @@
export function logger(...args: any[]) {
console.log('Pushy: ', ...args);
}
export function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}

View File

@@ -1,10 +1,11 @@
{
"name": "react-native-update",
"version": "9.1.0",
"version": "10.7.1",
"description": "react-native hot update",
"main": "lib/index.ts",
"main": "src/index",
"scripts": {
"prepublish": "yarn submodule",
"prepack": "yarn submodule && yarn lint",
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
"submodule": "git submodule update --init --recursive",
"test": "echo \"Error: no test specified\" && exit 1",
"build-lib": "yarn submodule && $ANDROID_HOME/ndk/20.1.5948944/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib",
@@ -39,30 +40,38 @@
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
},
"peerDependencies": {
"react-native": ">=0.57.0"
"react": ">=16.8.0",
"react-native": ">=0.59.0"
},
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
"dependencies": {
"nanoid": "^3.3.3"
},
"codegenConfig": {
"libraries": [
{
"name": "RCTPushySpec",
"type": "modules",
"jsSrcsDir": "lib"
}
]
"name": "RCTPushySpec",
"type": "modules",
"jsSrcsDir": "src"
},
"devDependencies": {
"@babel/core": "^7.24.0",
"@react-native/babel-preset": "^0.73.21",
"@react-native/eslint-config": "^0.73.2",
"@react-native/typescript-config": "^0.74.0",
"@types/fs-extra": "^9.0.13",
"@types/jest": "^29.2.1",
"@types/node": "^20.8.9",
"@types/react": "^18.2.46",
"detox": "^20.5.0",
"eslint": "^8.57.0",
"eslint-plugin-ft-flow": "^3.0.7",
"firebase-tools": "^11.24.1",
"fs-extra": "^9.1.0",
"jest": "^29.2.1",
"jest": "^29.7.0",
"pod-install": "^0.1.37",
"prettier": "^2",
"react": "18.2.0",
"react-native": "0.73",
"ts-jest": "^29.0.3",
"typescript": "^5.2.2"
"typescript": "^5.3.3"
}
}

View File

@@ -1,5 +1,7 @@
require 'json'
new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
Pod::Spec.new do |s|
@@ -40,5 +42,25 @@ Pod::Spec.new do |s|
'android/jni/lzma/C/Lzma2Dec.{h,c}']
ss.private_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
end
install_modules_dependencies(s)
if defined?(install_modules_dependencies()) != nil
install_modules_dependencies(s);
else
if new_arch_enabled
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
s.pod_target_xcconfig = {
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
}
s.dependency "React-Codegen"
s.dependency "RCT-Folly"
s.dependency "RCTRequired"
s.dependency "RCTTypeSafety"
s.dependency "ReactCommon/turbomodule/core"
end
end
end

View File

@@ -1,5 +1,4 @@
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
import { TurboModuleRegistry } from 'react-native';
import { TurboModule, TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
getConstants: () => {
@@ -9,14 +8,12 @@ export interface Spec extends TurboModule {
isFirstTime: boolean;
rolledBackVersion: string;
buildTime: string;
blockUpdate: Object;
uuid: string;
isUsingBundleUrl: boolean;
};
setLocalHashInfo(hash: string, info: string): Promise<void>;
getLocalHashInfo(hash: string): Promise<string>;
setUuid(uuid: string): Promise<void>;
setBlockUpdate(options: { reason: string; until: number }): Promise<void>;
reloadUpdate(options: { hash: string }): Promise<void>;
setNeedUpdate(options: { hash: string }): Promise<void>;
markSuccess(): Promise<void>;

409
src/client.ts Normal file
View File

@@ -0,0 +1,409 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { log, testUrls } from './utils';
import { EmitterSubscription, Platform } from 'react-native';
import { PermissionsAndroid } from './permissions';
import {
PushyModule,
buildTime,
cInfo,
pushyNativeEventEmitter,
currentVersion,
packageVersion,
rolledBackVersion,
setLocalHashInfo,
isRolledBack,
} from './core';
const defaultServer = {
main: 'https://update.react-native.cn/api',
backups: ['https://update.reactnative.cn/api'],
queryUrl:
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json',
};
const empty = {};
const noop = () => {};
if (Platform.OS === 'web') {
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
}
export class Pushy {
options: PushyOptions = {
appKey: '',
server: defaultServer,
autoMarkSuccess: true,
updateStrategy: 'alwaysAlert',
checkStrategy: 'both',
logger: noop,
debug: false,
};
lastChecking?: number;
lastRespJson?: Promise<any>;
progressHandlers: Record<string, EmitterSubscription> = {};
downloadedHash?: string;
marked = false;
applyingUpdate = false;
version = cInfo.pushy;
constructor(options: PushyOptions) {
if (Platform.OS === 'ios' || Platform.OS === 'android') {
if (!options.appKey) {
throw new Error('appKey is required');
}
}
this.setOptions(options);
}
setOptions = (options: Partial<PushyOptions>) => {
for (const [key, value] of Object.entries(options)) {
if (value !== undefined) {
// @ts-expect-error
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) => {
return `${endpoint}/checkUpdate/${this.options.appKey}`;
};
assertHash = (hash: string) => {
if (!this.downloadedHash) {
return;
}
if (hash !== this.downloadedHash) {
log(`use downloaded hash ${this.downloadedHash} first`);
return;
}
return true;
};
markSuccess = () => {
if (this.marked || __DEV__) {
return;
}
this.marked = true;
PushyModule.markSuccess();
this.report({ type: 'markSuccess' });
};
switchVersion = (hash: string) => {
if (__DEV__) {
console.warn(
'您调用了switchVersion方法但是当前是开发环境不会进行任何操作。',
);
return;
}
if (this.assertHash(hash) && !this.applyingUpdate) {
log('switchVersion: ' + hash);
this.applyingUpdate = true;
PushyModule.reloadUpdate({ hash });
}
};
switchVersionLater = (hash: string) => {
if (__DEV__) {
console.warn(
'您调用了switchVersionLater方法但是当前是开发环境不会进行任何操作。',
);
return;
}
if (this.assertHash(hash)) {
log('switchVersionLater: ' + hash);
PushyModule.setNeedUpdate({ hash });
}
};
checkUpdate = async () => {
if (__DEV__ && !this.options.debug) {
console.info(
'您当前处于开发环境且未启用 debug不会进行热更检查。如需在开发环境中调试热更请在 client 中设置 debug 为 true',
);
return;
}
if (Platform.OS === 'web') {
console.warn('web 端不支持热更新检查');
return;
}
const now = Date.now();
if (
this.lastRespJson &&
this.lastChecking &&
now - this.lastChecking < 1000 * 5
) {
return await this.lastRespJson;
}
this.lastChecking = now;
this.report({ type: 'checking' });
const fetchBody = {
packageVersion,
hash: currentVersion,
buildTime,
cInfo,
};
if (__DEV__) {
delete fetchBody.buildTime;
}
const fetchPayload = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(fetchBody),
};
let resp;
try {
resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e: any) {
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Trying backup endpoints.',
});
const backupEndpoints = await this.getBackupEndpoints();
if (backupEndpoints) {
try {
resp = await Promise.race(
backupEndpoints.map(endpoint =>
fetch(this.getCheckUrl(endpoint), fetchPayload),
),
);
} catch {}
}
}
if (!resp) {
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Please check your network.',
});
return this.lastRespJson ? await this.lastRespJson : empty;
}
this.lastRespJson = resp.json();
const result: CheckResult = await this.lastRespJson;
if (resp.status !== 200) {
this.report({
type: 'errorChecking',
message: result.message,
});
}
return result;
};
getBackupEndpoints = async () => {
const { server } = this.options;
if (!server) {
return [];
}
if (server.queryUrl) {
try {
const resp = await fetch(server.queryUrl);
const remoteEndpoints = await resp.json();
log('fetch endpoints:', remoteEndpoints);
if (Array.isArray(remoteEndpoints)) {
server.backups = Array.from(
new Set([...(server.backups || []), ...remoteEndpoints]),
);
}
} catch (e: any) {
log('failed to fetch endpoints from: ', server.queryUrl);
}
}
return server.backups;
};
downloadUpdate = async (
info: CheckResult,
onDownloadProgress?: (data: ProgressData) => void,
) => {
const {
hash,
diffUrl: _diffUrl,
diffUrls,
pdiffUrl: _pdiffUrl,
pdiffUrls,
updateUrl: _updateUrl,
updateUrls,
name,
description,
metaInfo,
} = info;
if (!info.update || !hash) {
return;
}
if (rolledBackVersion === hash) {
log(`rolledback hash ${rolledBackVersion}, ignored`);
return;
}
if (this.downloadedHash === hash) {
log(`duplicated downloaded hash ${this.downloadedHash}, ignored`);
return this.downloadedHash;
}
if (this.progressHandlers[hash]) {
return;
}
if (onDownloadProgress) {
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
'RCTPushyDownloadProgress',
progressData => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
let succeeded = false;
this.report({ type: 'downloading' });
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
if (diffUrl) {
log('downloading diff');
try {
await PushyModule.downloadPatchFromPpk({
updateUrl: diffUrl,
hash,
originHash: currentVersion,
});
succeeded = true;
} catch (e: any) {
if (__DEV__) {
succeeded = true;
} else {
log(`diff error: ${e.message}, try pdiff`);
}
}
}
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
if (!succeeded && pdiffUrl) {
log('downloading pdiff');
try {
await PushyModule.downloadPatchFromPackage({
updateUrl: pdiffUrl,
hash,
});
succeeded = true;
} catch (e: any) {
if (__DEV__) {
succeeded = true;
} else {
log(`pdiff error: ${e.message}, try full patch`);
}
}
}
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
if (!succeeded && updateUrl) {
log('downloading full patch');
try {
await PushyModule.downloadFullUpdate({
updateUrl: updateUrl,
hash,
});
succeeded = true;
} catch (e: any) {
if (__DEV__) {
succeeded = true;
} else {
log(`full patch error: ${e.message}`);
}
}
}
if (this.progressHandlers[hash]) {
this.progressHandlers[hash].remove();
delete this.progressHandlers[hash];
}
if (__DEV__) {
return hash;
}
if (!succeeded) {
return this.report({
type: 'errorUpdate',
data: { newVersion: hash },
});
}
log('downloaded hash:', hash);
setLocalHashInfo(hash, {
name,
description,
metaInfo,
});
this.downloadedHash = hash;
return hash;
};
downloadAndInstallApk = async (
url: string,
onDownloadProgress?: (data: ProgressData) => void,
) => {
if (Platform.OS !== 'android') {
return;
}
this.report({ type: 'downloadingApk' });
if (Platform.Version <= 23) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return this.report({ type: 'rejectStoragePermission' });
}
} catch (e: any) {
return this.report({ type: 'errorStoragePermission' });
}
}
const progressKey = 'downloadingApk';
if (onDownloadProgress) {
this.progressHandlers[progressKey] = pushyNativeEventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData: ProgressData) => {
if (progressData.hash === progressKey) {
onDownloadProgress(progressData);
}
},
);
}
await PushyModule.downloadAndInstallApk({
url,
target: 'update.apk',
hash: progressKey,
}).catch(() => {
this.report({ type: 'errowDownloadAndInstallApk' });
});
if (this.progressHandlers[progressKey]) {
this.progressHandlers[progressKey].remove();
delete this.progressHandlers[progressKey];
}
};
}

42
src/context.ts Normal file
View File

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

72
src/core.ts Normal file
View File

@@ -0,0 +1,72 @@
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { emptyModule, log } from './utils';
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
const isTurboModuleEnabled =
// @ts-expect-error
global.__turboModuleProxy != null;
export const PushyModule =
Platform.OS === 'web'
? emptyModule
: isTurboModuleEnabled
? require('./NativePushy').default
: NativeModules.Pushy;
if (!PushyModule) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
}
const PushyConstants = isTurboModuleEnabled
? PushyModule.getConstants()
: PushyModule;
export const downloadRootDir = PushyConstants.downloadRootDir;
export const packageVersion = PushyConstants.packageVersion;
export const currentVersion = PushyConstants.currentVersion;
export const isFirstTime = PushyConstants.isFirstTime;
export const rolledBackVersion = PushyConstants.rolledBackVersion;
export const isRolledBack = typeof rolledBackVersion === 'string';
export const buildTime = PushyConstants.buildTime;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
export function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
}
export async function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;
metaInfo?: string;
}> {
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
}
export const pushyNativeEventEmitter = new NativeEventEmitter(PushyModule);
if (!uuid) {
uuid = require('nanoid/non-secure').nanoid();
PushyModule.setUuid(uuid);
}
log('uuid: ' + uuid);
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,
};

3
src/index.ts Normal file
View File

@@ -0,0 +1,3 @@
export { Pushy } from './client';
export { PushyContext, usePushy } from './context';
export { PushyProvider } from './provider';

View File

@@ -0,0 +1 @@
export { PermissionsAndroid } from 'react-native';

4
src/permissions.ts Normal file
View File

@@ -0,0 +1,4 @@
import type { PermissionsAndroidStatic } from 'react-native';
import { emptyModule } from './utils';
export const PermissionsAndroid = emptyModule as PermissionsAndroidStatic;

259
src/provider.tsx Normal file
View File

@@ -0,0 +1,259 @@
import React, {
ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import {
Alert,
NativeEventSubscription,
AppState,
Platform,
Linking,
} from 'react-native';
import { Pushy } from './client';
import {
currentVersion,
isFirstTime,
packageVersion,
getCurrentVersionInfo,
} from './core';
import { CheckResult, ProgressData } from './type';
import { PushyContext } from './context';
export const PushyProvider = ({
client,
children,
}: {
client: Pushy;
children: ReactNode;
}) => {
const { options } = client;
const stateListener = useRef<NativeEventSubscription>();
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
const updateInfoRef = useRef(updateInfo);
const [progress, setProgress] = useState<ProgressData>();
const [lastError, setLastError] = useState<Error>();
const lastChecking = useRef(0);
const dismissError = useCallback(() => {
setLastError(undefined);
}, []);
const alertUpdate = useCallback(
(...args: Parameters<typeof Alert.alert>) => {
if (
options.updateStrategy === 'alwaysAlert' ||
options.updateStrategy === 'alertUpdateAndIgnoreError'
) {
Alert.alert(...args);
}
},
[options.updateStrategy],
);
const alertError = useCallback(
(...args: Parameters<typeof Alert.alert>) => {
if (options.updateStrategy === 'alwaysAlert') {
Alert.alert(...args);
}
},
[options.updateStrategy],
);
const switchVersion = useCallback(() => {
if (updateInfo && updateInfo.hash) {
client.switchVersion(updateInfo.hash);
}
}, [client, updateInfo]);
const switchVersionLater = useCallback(() => {
if (updateInfo && updateInfo.hash) {
client.switchVersionLater(updateInfo.hash);
}
}, [client, updateInfo]);
const downloadUpdate = useCallback(
async (info: CheckResult | undefined = updateInfoRef.current) => {
if (!info || !info.update) {
return;
}
try {
const hash = await client.downloadUpdate(info, setProgress);
if (!hash) {
return;
}
stateListener.current && stateListener.current.remove();
if (options.updateStrategy === 'silentAndNow') {
return client.switchVersion(hash);
} else if (options.updateStrategy === 'silentAndLater') {
return client.switchVersionLater(hash);
}
alertUpdate('提示', '下载完毕,是否立即更新?', [
{
text: '下次再说',
style: 'cancel',
onPress: () => {
client.switchVersionLater(hash);
},
},
{
text: '立即更新',
style: 'default',
onPress: () => {
client.switchVersion(hash);
},
},
]);
} catch (e: any) {
setLastError(e);
alertError('更新失败', e.message);
}
},
[alertError, client, options.updateStrategy, alertUpdate],
);
const downloadAndInstallApk = useCallback(
async (downloadUrl: string) => {
if (Platform.OS === 'android' && downloadUrl) {
await client.downloadAndInstallApk(downloadUrl, setProgress);
}
},
[client],
);
const checkUpdate = useCallback(async () => {
const now = Date.now();
if (lastChecking.current && now - lastChecking.current < 1000) {
return;
}
lastChecking.current = now;
let info: CheckResult;
try {
info = await client.checkUpdate();
} catch (e: any) {
setLastError(e);
alertError('更新检查失败', e.message);
return;
}
if (!info) {
return;
}
updateInfoRef.current = info;
setUpdateInfo(info);
if (info.expired) {
const { downloadUrl } = info;
if (downloadUrl) {
if (options.updateStrategy === 'silentAndNow') {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl);
} else {
Linking.openURL(downloadUrl);
}
return;
}
alertUpdate('提示', '您的应用版本已更新,点击更新下载安装新版本', [
{
text: '更新',
onPress: () => {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl);
} else {
Linking.openURL(downloadUrl);
}
},
},
]);
}
} else if (info.update) {
if (
options.updateStrategy === 'silentAndNow' ||
options.updateStrategy === 'silentAndLater'
) {
return downloadUpdate(info);
}
alertUpdate(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
[
{ text: '取消', style: 'cancel' },
{
text: '确定',
style: 'default',
onPress: () => {
downloadUpdate();
},
},
],
);
}
}, [
alertError,
client,
downloadAndInstallApk,
downloadUpdate,
options.updateStrategy,
alertUpdate,
]);
const markSuccess = client.markSuccess;
useEffect(() => {
if (__DEV__ && !options.debug) {
console.info(
'您当前处于开发环境且未启用debug不会进行热更检查。如需在开发环境中调试热更请在client中设置debug为true',
);
return;
}
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
if (isFirstTime && autoMarkSuccess) {
markSuccess();
}
if (checkStrategy === 'both' || checkStrategy === 'onAppResume') {
stateListener.current = AppState.addEventListener(
'change',
nextAppState => {
if (nextAppState === 'active') {
checkUpdate();
}
},
);
}
if (checkStrategy === 'both' || checkStrategy === 'onAppStart') {
checkUpdate();
}
let dismissErrorTimer: ReturnType<typeof setTimeout>;
if (typeof dismissErrorAfter === 'number' && dismissErrorAfter > 0) {
dismissErrorTimer = setTimeout(() => {
dismissError();
}, dismissErrorAfter);
}
return () => {
stateListener.current && stateListener.current.remove();
clearTimeout(dismissErrorTimer);
};
}, [checkUpdate, options, dismissError, markSuccess]);
return (
<PushyContext.Provider
value={{
checkUpdate,
switchVersion,
switchVersionLater,
dismissError,
updateInfo,
lastError,
markSuccess,
client,
downloadUpdate,
packageVersion,
currentHash: currentVersion,
progress,
downloadAndInstallApk,
getCurrentVersionInfo,
}}>
{children}
</PushyContext.Provider>
);
};

82
src/type.ts Normal file
View File

@@ -0,0 +1,82 @@
export interface CheckResult {
upToDate?: true;
expired?: true;
downloadUrl?: string;
update?: true;
name?: string; // version name
hash?: string;
description?: string;
metaInfo?: string;
pdiffUrl?: string;
pdiffUrls?: string[];
diffUrl?: string;
diffUrls?: string[];
updateUrl?: string;
updateUrls?: string[];
paused?: 'app' | 'package';
message?: string;
}
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 UpdateEventsLogger = ({
type,
data,
}: {
type: EventType;
data: EventData;
}) => void;
export interface PushyServerConfig {
main: string;
backups?: string[];
queryUrl?: string;
}
export interface PushyOptions {
appKey: string;
server?: PushyServerConfig;
logger?: UpdateEventsLogger;
updateStrategy?:
| 'alwaysAlert'
| 'alertUpdateAndIgnoreError'
| 'silentAndNow'
| 'silentAndLater'
| null;
checkStrategy?: 'onAppStart' | 'onAppResume' | 'both' | null;
autoMarkSuccess?: boolean;
dismissErrorAfter?: number;
debug?: boolean;
}

39
src/utils.ts Normal file
View File

@@ -0,0 +1,39 @@
import { Platform } from 'react-native';
export function log(...args: any[]) {
console.log('pushy: ', ...args);
}
const noop = () => {};
class EmptyModule {
constructor() {
return new Proxy(this, {
get() {
return noop;
},
});
}
}
export const emptyModule = new EmptyModule();
const ping =
Platform.OS === 'web'
? Promise.resolve
: async (url: string) =>
Promise.race([
fetch(url, {
method: 'HEAD',
})
.then(({ status }) => (status === 200 ? url : null))
.catch(() => null),
new Promise(r => setTimeout(() => r(null), 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(ping)).catch(() => null);
};

6
tea.yaml Normal file
View File

@@ -0,0 +1,6 @@
# https://tea.xyz/what-is-this-file
---
version: 1.0.0
codeOwners:
- '0x10D90dC0034E2e82F0AC55954B3ed4EC0550ECe7'
quorum: 1

4
tsconfig.json Normal file
View File

@@ -0,0 +1,4 @@
{
"extends": "@react-native/typescript-config/tsconfig.json",
"include": ["src/**/*"]
}

4834
yarn.lock

File diff suppressed because it is too large Load Diff