mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-17 23:36:11 +08:00
Compare commits
54 Commits
v10.0.0-be
...
v10.4.0
Author | SHA1 | Date | |
---|---|---|---|
![]() |
571c2819b9 | ||
![]() |
1f75688b92 | ||
![]() |
de332c1796 | ||
![]() |
80e0451983 | ||
![]() |
b512ae18b7 | ||
![]() |
fe75a2ca9e | ||
![]() |
d84ad103fb | ||
![]() |
208034fa7d | ||
![]() |
c6430a9ed4 | ||
![]() |
f2aec36705 | ||
![]() |
71e5b947d3 | ||
![]() |
5dc8d8defc | ||
![]() |
30687dddf2 | ||
![]() |
57ddcc7758 | ||
![]() |
a93bbe553d | ||
![]() |
356050d839 | ||
![]() |
5df3cb65b3 | ||
![]() |
699eb0ea05 | ||
![]() |
36c4ff085c | ||
![]() |
8c13dd69b1 | ||
![]() |
2df04cb377 | ||
![]() |
e39d4fa370 | ||
![]() |
94cf96a0e5 | ||
![]() |
22c4b01ead | ||
![]() |
f655a1d954 | ||
![]() |
2bdc64ba1b | ||
![]() |
f5242017b9 | ||
![]() |
42e2051290 | ||
![]() |
a66f354c3b | ||
![]() |
592e13b77b | ||
![]() |
2845a4302a | ||
![]() |
84ef668102 | ||
![]() |
c63e1501fe | ||
![]() |
45bfa2560e | ||
![]() |
ab9c40bf2e | ||
![]() |
d184beabaf | ||
![]() |
68a6235145 | ||
![]() |
a98a48d665 | ||
![]() |
4bf004a274 | ||
![]() |
f01716bcb2 | ||
![]() |
4f9e1495c8 | ||
![]() |
9c06bac91b | ||
![]() |
4923aff184 | ||
![]() |
f6a38c1f48 | ||
![]() |
92cfbb3fdf | ||
![]() |
64ef8e129d | ||
![]() |
ce51b2ca81 | ||
![]() |
6c1662fce1 | ||
![]() |
d9e4575964 | ||
![]() |
190103687c | ||
![]() |
f6f055be64 | ||
![]() |
05e5c5a1a7 | ||
![]() |
296498e20a | ||
![]() |
2a3b8e5707 |
4
.eslintrc.js
Normal file
4
.eslintrc.js
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
module.exports = {
|
||||||
|
root: true,
|
||||||
|
extends: '@react-native',
|
||||||
|
};
|
@@ -41,14 +41,17 @@ export const testFunctionDefaultRegion = functions.https.onCall(data => {
|
|||||||
|
|
||||||
const { type, asError, inputData } = data;
|
const { type, asError, inputData } = data;
|
||||||
if (!Object.hasOwnProperty.call(SAMPLE_DATA, type)) {
|
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];
|
const outputData = SAMPLE_DATA[type];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
assert.deepEqual(outputData, inputData);
|
assert.deepEqual(outputData, inputData);
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
throw new functions.https.HttpsError(
|
throw new functions.https.HttpsError(
|
||||||
'invalid-argument',
|
'invalid-argument',
|
||||||
|
@@ -47,4 +47,6 @@ Example
|
|||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
domains.json
|
domains.json
|
||||||
endpoints.json
|
endpoints.json
|
||||||
|
|
||||||
|
tea.yaml
|
@@ -1,4 +1,6 @@
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
trailingComma: 'all',
|
arrowParens: 'avoid',
|
||||||
|
bracketSameLine: true,
|
||||||
singleQuote: true,
|
singleQuote: true,
|
||||||
|
trailingComma: 'all',
|
||||||
};
|
};
|
||||||
|
@@ -28,14 +28,7 @@ describe('测试Native模块的方法', () => {
|
|||||||
await element(by.id('done')).longPress();
|
await element(by.id('done')).longPress();
|
||||||
await expect(element(by.id('done'))).toBeNotVisible();
|
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') {
|
if (device.getPlatform() === 'android') {
|
||||||
it('reloadUpdate', async () => {
|
it('reloadUpdate', async () => {
|
||||||
await element(by.id('reloadUpdate')).longPress();
|
await element(by.id('reloadUpdate')).longPress();
|
||||||
|
@@ -284,17 +284,19 @@ PODS:
|
|||||||
- React-jsinspector (0.69.8)
|
- React-jsinspector (0.69.8)
|
||||||
- React-logger (0.69.8):
|
- React-logger (0.69.8):
|
||||||
- glog
|
- 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
|
||||||
- React-Core
|
- React-Core
|
||||||
- react-native-update/HDiffPatch (= 9.0.0)
|
- react-native-update/HDiffPatch (= 10.0.0-beta.1)
|
||||||
- react-native-update/RCTPushy (= 9.0.0)
|
- react-native-update/RCTPushy (= 10.0.0-beta.1)
|
||||||
- SSZipArchive
|
- SSZipArchive
|
||||||
- react-native-update/HDiffPatch (9.0.0):
|
- react-native-update/HDiffPatch (10.0.0-beta.1):
|
||||||
- React
|
- React
|
||||||
- React-Core
|
- React-Core
|
||||||
- SSZipArchive
|
- SSZipArchive
|
||||||
- react-native-update/RCTPushy (9.0.0):
|
- react-native-update/RCTPushy (10.0.0-beta.1):
|
||||||
- React
|
- React
|
||||||
- React-Core
|
- React-Core
|
||||||
- SSZipArchive
|
- SSZipArchive
|
||||||
@@ -364,6 +366,8 @@ PODS:
|
|||||||
- React-jsi (= 0.69.8)
|
- React-jsi (= 0.69.8)
|
||||||
- React-logger (= 0.69.8)
|
- React-logger (= 0.69.8)
|
||||||
- React-perflogger (= 0.69.8)
|
- React-perflogger (= 0.69.8)
|
||||||
|
- RNVectorIcons (10.0.3):
|
||||||
|
- React-Core
|
||||||
- SocketRocket (0.6.0)
|
- SocketRocket (0.6.0)
|
||||||
- SSZipArchive (2.4.3)
|
- SSZipArchive (2.4.3)
|
||||||
- Yoga (1.14.0)
|
- Yoga (1.14.0)
|
||||||
@@ -414,6 +418,7 @@ DEPENDENCIES:
|
|||||||
- React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`)
|
- React-jsiexecutor (from `../node_modules/react-native/ReactCommon/jsiexecutor`)
|
||||||
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
|
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
|
||||||
- React-logger (from `../node_modules/react-native/ReactCommon/logger`)
|
- 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-native-update (from `../node_modules/react-native-update`)
|
||||||
- React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`)
|
- React-perflogger (from `../node_modules/react-native/ReactCommon/reactperflogger`)
|
||||||
- React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`)
|
- React-RCTActionSheet (from `../node_modules/react-native/Libraries/ActionSheetIOS`)
|
||||||
@@ -427,6 +432,7 @@ DEPENDENCIES:
|
|||||||
- React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`)
|
- React-RCTVibration (from `../node_modules/react-native/Libraries/Vibration`)
|
||||||
- React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`)
|
- React-runtimeexecutor (from `../node_modules/react-native/ReactCommon/runtimeexecutor`)
|
||||||
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
|
- 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`)
|
- Yoga (from `../node_modules/react-native/ReactCommon/yoga`)
|
||||||
|
|
||||||
SPEC REPOS:
|
SPEC REPOS:
|
||||||
@@ -487,6 +493,8 @@ EXTERNAL SOURCES:
|
|||||||
:path: "../node_modules/react-native/ReactCommon/jsinspector"
|
:path: "../node_modules/react-native/ReactCommon/jsinspector"
|
||||||
React-logger:
|
React-logger:
|
||||||
:path: "../node_modules/react-native/ReactCommon/logger"
|
:path: "../node_modules/react-native/ReactCommon/logger"
|
||||||
|
react-native-safe-area-context:
|
||||||
|
:path: "../node_modules/react-native-safe-area-context"
|
||||||
react-native-update:
|
react-native-update:
|
||||||
:path: "../node_modules/react-native-update"
|
:path: "../node_modules/react-native-update"
|
||||||
React-perflogger:
|
React-perflogger:
|
||||||
@@ -513,6 +521,8 @@ EXTERNAL SOURCES:
|
|||||||
:path: "../node_modules/react-native/ReactCommon/runtimeexecutor"
|
:path: "../node_modules/react-native/ReactCommon/runtimeexecutor"
|
||||||
ReactCommon:
|
ReactCommon:
|
||||||
:path: "../node_modules/react-native/ReactCommon"
|
:path: "../node_modules/react-native/ReactCommon"
|
||||||
|
RNVectorIcons:
|
||||||
|
:path: "../node_modules/react-native-vector-icons"
|
||||||
Yoga:
|
Yoga:
|
||||||
:path: "../node_modules/react-native/ReactCommon/yoga"
|
:path: "../node_modules/react-native/ReactCommon/yoga"
|
||||||
|
|
||||||
@@ -549,7 +559,8 @@ SPEC CHECKSUMS:
|
|||||||
React-jsiexecutor: 2cf8ea3753afb81dfcc386613dbbb0b5d155fb34
|
React-jsiexecutor: 2cf8ea3753afb81dfcc386613dbbb0b5d155fb34
|
||||||
React-jsinspector: 0eda09e9cf22bbb5dbb1d23143b03a31acf37d67
|
React-jsinspector: 0eda09e9cf22bbb5dbb1d23143b03a31acf37d67
|
||||||
React-logger: 5997ab008583826c10ffe4e1ff990363e975639d
|
React-logger: 5997ab008583826c10ffe4e1ff990363e975639d
|
||||||
react-native-update: 2b5ef06bfeaa668614c8deb7ec4d20dcf56f9278
|
react-native-safe-area-context: 0ee144a6170530ccc37a0fd9388e28d06f516a89
|
||||||
|
react-native-update: 767449a2cf592387b9aecb97980ec0536d72c890
|
||||||
React-perflogger: ad1416a715d86b32f456e5d0aed99c3b52f1de37
|
React-perflogger: ad1416a715d86b32f456e5d0aed99c3b52f1de37
|
||||||
React-RCTActionSheet: cbf7c6a953982562418ee72a1084ff7b9447b558
|
React-RCTActionSheet: cbf7c6a953982562418ee72a1084ff7b9447b558
|
||||||
React-RCTAnimation: 33df3e25824dd7313edec28dded2745542f9352b
|
React-RCTAnimation: 33df3e25824dd7313edec28dded2745542f9352b
|
||||||
@@ -562,6 +573,7 @@ SPEC CHECKSUMS:
|
|||||||
React-RCTVibration: 5462287ee85304ba1a00474665ab292e63a41663
|
React-RCTVibration: 5462287ee85304ba1a00474665ab292e63a41663
|
||||||
React-runtimeexecutor: 9df680f18497367bcf5c15b6b6406c0f2dfa2b6a
|
React-runtimeexecutor: 9df680f18497367bcf5c15b6b6406c0f2dfa2b6a
|
||||||
ReactCommon: c10f046f3ef8561e7c8e7e9b9dae2ecc9ffc48ef
|
ReactCommon: c10f046f3ef8561e7c8e7e9b9dae2ecc9ffc48ef
|
||||||
|
RNVectorIcons: bc7ee28cadf39c77a49232a14738dfce690f66cd
|
||||||
SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608
|
SocketRocket: fccef3f9c5cedea1353a9ef6ada904fde10d6608
|
||||||
SSZipArchive: fe6a26b2a54d5a0890f2567b5cc6de5caa600aef
|
SSZipArchive: fe6a26b2a54d5a0890f2567b5cc6de5caa600aef
|
||||||
Yoga: d3820731e0ca3a4933f061ad29defaf7726e3251
|
Yoga: d3820731e0ca3a4933f061ad29defaf7726e3251
|
||||||
@@ -569,4 +581,4 @@ SPEC CHECKSUMS:
|
|||||||
|
|
||||||
PODFILE CHECKSUM: 618d17df10f335f1d113daac849a7997894646b2
|
PODFILE CHECKSUM: 618d17df10f335f1d113daac849a7997894646b2
|
||||||
|
|
||||||
COCOAPODS: 1.11.3
|
COCOAPODS: 1.14.3
|
||||||
|
@@ -1,12 +1,12 @@
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
const extraNodeModules = {
|
// const extraNodeModules = {
|
||||||
react: path.resolve(__dirname, 'node_modules/react'),
|
// react: path.resolve(__dirname, 'node_modules/react'),
|
||||||
'react-native': path.resolve(__dirname, 'node_modules/react-native'),
|
// 'react-native': path.resolve(__dirname, 'node_modules/react-native'),
|
||||||
'react-native-update': path.resolve(__dirname, '../..'),
|
// 'react-native-update': path.resolve(__dirname, '../..'),
|
||||||
'@babel/runtime': path.resolve(__dirname, 'node_modules/@babel/runtime'),
|
// '@babel/runtime': path.resolve(__dirname, 'node_modules/@babel/runtime'),
|
||||||
};
|
// };
|
||||||
const watchFolders = [path.resolve(__dirname, '../..')];
|
// const watchFolders = [path.resolve(__dirname, '../..')];
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
transformer: {
|
transformer: {
|
||||||
@@ -17,8 +17,8 @@ module.exports = {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
resolver: {
|
// resolver: {
|
||||||
extraNodeModules,
|
// extraNodeModules,
|
||||||
},
|
// },
|
||||||
watchFolders,
|
// watchFolders,
|
||||||
};
|
};
|
||||||
|
@@ -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": "link:../..",
|
"react-native-update": "^10.2.6",
|
||||||
"react-native-vector-icons": "^10.0.3"
|
"react-native-vector-icons": "^10.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
@@ -19,23 +19,25 @@ const UUID = '00000000-0000-0000-0000-000000000000';
|
|||||||
const DownloadUrl =
|
const DownloadUrl =
|
||||||
'http://cos.pgyer.com/697913e94d7441f20c686e2b0996a1aa.apk?sign=7a8f11b1df82cba45c8ac30b1acec88c&t=1680404102&response-content-disposition=attachment%3Bfilename%3DtestHotupdate_1.0.apk';
|
'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}) => {
|
return (
|
||||||
if (!visible) {
|
<View style={styles.overlay}>
|
||||||
return null;
|
<View style={styles.dialog}>
|
||||||
}
|
<Text style={styles.title}>{title}</Text>
|
||||||
|
<TouchableOpacity
|
||||||
return (
|
testID="done"
|
||||||
<View style={styles.overlay}>
|
style={styles.button}
|
||||||
<View style={styles.dialog}>
|
onLongPress={onConfirm}>
|
||||||
<Text style={styles.title}>{title}</Text>
|
<Text style={styles.buttonText}>确认</Text>
|
||||||
<TouchableOpacity testID='done' style={styles.button} onLongPress={onConfirm}>
|
</TouchableOpacity>
|
||||||
<Text style={styles.buttonText}>确认</Text>
|
|
||||||
</TouchableOpacity>
|
|
||||||
</View>
|
|
||||||
</View>
|
</View>
|
||||||
);
|
</View>
|
||||||
};
|
);
|
||||||
|
};
|
||||||
export default function TestConsole({visible}) {
|
export default function TestConsole({visible}) {
|
||||||
const [text, setText] = useState('');
|
const [text, setText] = useState('');
|
||||||
const [running, setRunning] = useState(false);
|
const [running, setRunning] = useState(false);
|
||||||
@@ -64,13 +66,6 @@ export default function TestConsole({visible}) {
|
|||||||
setText(`setUuid\n${UUID}`);
|
setText(`setUuid\n${UUID}`);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
name: 'setBlockUpdate',
|
|
||||||
invoke: () => {
|
|
||||||
setText('setBlockUpdate');
|
|
||||||
setOptions({reason: 'application has been block', until: 1673082950});
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
name: 'reloadUpdate',
|
name: 'reloadUpdate',
|
||||||
invoke: () => {
|
invoke: () => {
|
||||||
@@ -132,9 +127,8 @@ export default function TestConsole({visible}) {
|
|||||||
testID={NativeTestMethod[i].name}
|
testID={NativeTestMethod[i].name}
|
||||||
onLongPress={() => {
|
onLongPress={() => {
|
||||||
NativeTestMethod[i].invoke();
|
NativeTestMethod[i].invoke();
|
||||||
}}
|
}}>
|
||||||
>
|
<Text>{NativeTestMethod[i].name}</Text>
|
||||||
<Text>{NativeTestMethod[i].name}</Text>
|
|
||||||
</TouchableOpacity>,
|
</TouchableOpacity>,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -164,8 +158,14 @@ export default function TestConsole({visible}) {
|
|||||||
/>
|
/>
|
||||||
{running && <ActivityIndicator />}
|
{running && <ActivityIndicator />}
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
style={{backgroundColor:'rgb(0,140,237)', justifyContent: 'center',
|
style={{
|
||||||
alignItems: 'center',paddingTop:10,paddingBottom:10,marginBottom:5}}
|
backgroundColor: 'rgb(0,140,237)',
|
||||||
|
justifyContent: 'center',
|
||||||
|
alignItems: 'center',
|
||||||
|
paddingTop: 10,
|
||||||
|
paddingBottom: 10,
|
||||||
|
marginBottom: 5,
|
||||||
|
}}
|
||||||
testID="submit"
|
testID="submit"
|
||||||
onLongPress={async () => {
|
onLongPress={async () => {
|
||||||
setRunning(true);
|
setRunning(true);
|
||||||
@@ -195,17 +195,18 @@ export default function TestConsole({visible}) {
|
|||||||
setAlertMsg(e.message);
|
setAlertMsg(e.message);
|
||||||
}
|
}
|
||||||
setRunning(false);
|
setRunning(false);
|
||||||
}}
|
}}>
|
||||||
>
|
<Text style={{color: 'white'}}>执行</Text>
|
||||||
<Text style={{color:'white'}}>执行</Text>
|
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
<Button title="重置" onPress={() => setText('')} />
|
<Button title="重置" onPress={() => setText('')} />
|
||||||
{renderTestView()}
|
{renderTestView()}
|
||||||
<CustomDialog
|
<CustomDialog
|
||||||
title={alertMsg}
|
title={alertMsg}
|
||||||
visible={alertVisible}
|
visible={alertVisible}
|
||||||
onConfirm={()=>{setAlertVisible(false)}}
|
onConfirm={() => {
|
||||||
/>
|
setAlertVisible(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
</SafeAreaView>
|
</SafeAreaView>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
@@ -24,29 +24,35 @@ function App() {
|
|||||||
switchVersionLater,
|
switchVersionLater,
|
||||||
switchVersion,
|
switchVersion,
|
||||||
updateInfo,
|
updateInfo,
|
||||||
|
packageVersion,
|
||||||
|
currentHash,
|
||||||
progress: {received, total} = {},
|
progress: {received, total} = {},
|
||||||
} = usePushy();
|
} = usePushy();
|
||||||
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
|
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
|
||||||
|
const [showTestConsole, setShowTestConsole] = useState(false);
|
||||||
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
|
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
|
||||||
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
|
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
|
||||||
const snackbarVisible =
|
const snackbarVisible =
|
||||||
showUpdateSnackbar &&
|
!useDefaultAlert && showUpdateSnackbar && updateInfo?.update;
|
||||||
updateInfo &&
|
|
||||||
updateInfo.updateAvailable &&
|
|
||||||
!useDefaultAlert;
|
|
||||||
return (
|
return (
|
||||||
<View style={styles.container}>
|
<View style={styles.container}>
|
||||||
<Text style={styles.welcome}>欢迎使用Pushy热更新服务</Text>
|
<Text style={styles.welcome}>欢迎使用Pushy热更新服务</Text>
|
||||||
<Switch
|
<View style={{flexDirection: 'row'}}>
|
||||||
value={useCustomUi}
|
<Text>
|
||||||
onValueChange={v => {
|
{useDefaultAlert ? '当前使用' : '当前不使用'}默认的alert更新提示
|
||||||
setUseDefaultAlert(v);
|
</Text>
|
||||||
client.setOptions({
|
<Switch
|
||||||
showAlert: v,
|
value={useDefaultAlert}
|
||||||
});
|
onValueChange={v => {
|
||||||
}}>
|
setUseDefaultAlert(v);
|
||||||
{useDefaultAlert ? '当前使用' : '当前不使用'}默认的alert更新提示
|
client?.setOptions({
|
||||||
</Switch>
|
useAlert: v,
|
||||||
|
});
|
||||||
|
setShowUpdateSnackbar(!v);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</View>
|
||||||
<Image
|
<Image
|
||||||
resizeMode={'contain'}
|
resizeMode={'contain'}
|
||||||
source={require('./assets/shezhi.png')}
|
source={require('./assets/shezhi.png')}
|
||||||
@@ -56,13 +62,17 @@ function App() {
|
|||||||
这是版本一 {'\n'}
|
这是版本一 {'\n'}
|
||||||
当前原生包版本号: {packageVersion}
|
当前原生包版本号: {packageVersion}
|
||||||
{'\n'}
|
{'\n'}
|
||||||
当前热更新版本Hash: {currentVersion || '(空)'}
|
当前热更新版本Hash: {currentHash || '(空)'}
|
||||||
{'\n'}
|
{'\n'}
|
||||||
</Text>
|
</Text>
|
||||||
<Text>
|
<Text>
|
||||||
下载进度:{received} / {total}
|
下载进度:{received} / {total}
|
||||||
</Text>
|
</Text>
|
||||||
<TouchableOpacity onPress={checkUpdate}>
|
<TouchableOpacity
|
||||||
|
onPress={() => {
|
||||||
|
checkUpdate();
|
||||||
|
setShowUpdateSnackbar(true);
|
||||||
|
}}>
|
||||||
<Text style={styles.instructions}>点击这里检查更新</Text>
|
<Text style={styles.instructions}>点击这里检查更新</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
|
|
||||||
@@ -70,29 +80,34 @@ function App() {
|
|||||||
testID="testcase"
|
testID="testcase"
|
||||||
style={{marginTop: 15}}
|
style={{marginTop: 15}}
|
||||||
onLongPress={() => {
|
onLongPress={() => {
|
||||||
this.setState({showTestConsole: true});
|
setShowTestConsole(true);
|
||||||
}}>
|
}}>
|
||||||
<Text style={styles.instructions}>
|
<Text style={styles.instructions}>
|
||||||
react-native-update版本:{client.version}
|
react-native-update版本:{client?.version}
|
||||||
</Text>
|
</Text>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
<TestConsole visible={showTestConsole} />
|
<TestConsole visible={showTestConsole} />
|
||||||
<Snackbar
|
{snackbarVisible && (
|
||||||
visible={snackbarVisible}
|
<Snackbar
|
||||||
onDismiss={() => {
|
visible={snackbarVisible}
|
||||||
setShowUpdateSnackbar(false);
|
onDismiss={() => {
|
||||||
}}
|
|
||||||
action={{
|
|
||||||
label: '更新',
|
|
||||||
onPress: async () => {
|
|
||||||
setShowUpdateSnackbar(false);
|
setShowUpdateSnackbar(false);
|
||||||
await downloadUpdate();
|
}}
|
||||||
setShowUpdateBanner(true);
|
action={{
|
||||||
},
|
label: '更新',
|
||||||
}}>
|
onPress: async () => {
|
||||||
有新版本({updateInfo.version})可用,是否更新?
|
setShowUpdateSnackbar(false);
|
||||||
</Snackbar>
|
await downloadUpdate();
|
||||||
|
setShowUpdateBanner(true);
|
||||||
|
},
|
||||||
|
}}>
|
||||||
|
<Text style={{color: 'white'}}>
|
||||||
|
有新版本({updateInfo.name})可用,是否更新?
|
||||||
|
</Text>
|
||||||
|
</Snackbar>
|
||||||
|
)}
|
||||||
<Banner
|
<Banner
|
||||||
|
style={{width: '100%', position: 'absolute', top: 0}}
|
||||||
visible={showUpdateBanner}
|
visible={showUpdateBanner}
|
||||||
actions={[
|
actions={[
|
||||||
{
|
{
|
||||||
@@ -138,7 +153,6 @@ const styles = StyleSheet.create({
|
|||||||
|
|
||||||
const pushyClient = new Pushy({
|
const pushyClient = new Pushy({
|
||||||
appKey,
|
appKey,
|
||||||
showAlert: false,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function Root() {
|
export default function Root() {
|
@@ -1,10 +1,10 @@
|
|||||||
{
|
{
|
||||||
"ios": {
|
"ios": {
|
||||||
"appId": 10976,
|
"appId": 24794,
|
||||||
"appKey": "p5q_rPYNOE0WdCf-i9ZCGPw-DUGUCMvY"
|
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
|
||||||
},
|
},
|
||||||
"android": {
|
"android": {
|
||||||
"appId": 10977,
|
"appId": 27509,
|
||||||
"appKey": "bUYKfZgtC9VirZsQbAt8qken2Gq2uxe3"
|
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -6231,9 +6231,12 @@ 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@link:../..":
|
react-native-update@^10.2.6:
|
||||||
version "0.0.0"
|
version "10.2.6"
|
||||||
uid ""
|
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.2.6.tgz#976c1d1b48ac3522677b5ecbfe3e64fa04df1839"
|
||||||
|
integrity sha512-x72ga106wEWsinHSN/ANk+YygvGq6hyTEVOCibakps7Wb+5JgTiMeE0p2+GOOPhuxMavEHiil5WdhYOipI3/Qg==
|
||||||
|
dependencies:
|
||||||
|
nanoid "^3.3.3"
|
||||||
|
|
||||||
react-native-vector-icons@^10.0.3:
|
react-native-vector-icons@^10.0.3:
|
||||||
version "10.0.3"
|
version "10.0.3"
|
||||||
|
@@ -69,13 +69,6 @@ public class UpdateContext {
|
|||||||
return context.getString(R.string.pushy_build_time);
|
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() {
|
public boolean getIsUsingBundleUrl() {
|
||||||
return isUsingBundleUrl;
|
return isUsingBundleUrl;
|
||||||
}
|
}
|
||||||
@@ -166,13 +159,6 @@ public class UpdateContext {
|
|||||||
return sp.getString(key, null);
|
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() {
|
public String getCurrentVersion() {
|
||||||
return sp.getString("currentVersion", null);
|
return sp.getString("currentVersion", null);
|
||||||
}
|
}
|
||||||
|
@@ -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) {
|
public static void setUuid(UpdateContext updateContext, String uuid, Promise promise) {
|
||||||
try {
|
try {
|
||||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||||
|
@@ -14,7 +14,7 @@ import java.io.File;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class UpdateModule extends NativeUpdateSpec {
|
public class UpdateModule extends NativePushySpec {
|
||||||
UpdateContext updateContext;
|
UpdateContext updateContext;
|
||||||
public static ReactApplicationContext mContext;
|
public static ReactApplicationContext mContext;
|
||||||
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
|
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
|
||||||
@@ -45,7 +45,6 @@ public class UpdateModule extends NativeUpdateSpec {
|
|||||||
if (rolledBackVersion != null) {
|
if (rolledBackVersion != null) {
|
||||||
updateContext.clearRollbackMark();
|
updateContext.clearRollbackMark();
|
||||||
}
|
}
|
||||||
constants.put("blockUpdate", updateContext.getBlockUpdate());
|
|
||||||
constants.put("uuid", updateContext.getKv("uuid"));
|
constants.put("uuid", updateContext.getKv("uuid"));
|
||||||
return constants;
|
return constants;
|
||||||
}
|
}
|
||||||
@@ -108,11 +107,6 @@ public class UpdateModule extends NativeUpdateSpec {
|
|||||||
UpdateModuleImpl.markSuccess(updateContext,promise);
|
UpdateModuleImpl.markSuccess(updateContext,promise);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setBlockUpdate(ReadableMap options,Promise promise) {
|
|
||||||
UpdateModuleImpl.setBlockUpdate(updateContext,options,promise);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void setUuid(final String uuid, Promise promise) {
|
public void setUuid(final String uuid, Promise promise) {
|
||||||
UpdateModuleImpl.setUuid(updateContext,uuid,promise);
|
UpdateModuleImpl.setUuid(updateContext,uuid,promise);
|
||||||
|
@@ -59,7 +59,6 @@ public class UpdateModule extends ReactContextBaseJavaModule {
|
|||||||
if (rolledBackVersion != null) {
|
if (rolledBackVersion != null) {
|
||||||
updateContext.clearRollbackMark();
|
updateContext.clearRollbackMark();
|
||||||
}
|
}
|
||||||
constants.put("blockUpdate", updateContext.getBlockUpdate());
|
|
||||||
constants.put("uuid", updateContext.getKv("uuid"));
|
constants.put("uuid", updateContext.getKv("uuid"));
|
||||||
return constants;
|
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
|
@ReactMethod
|
||||||
public void setUuid(final String uuid) {
|
public void setUuid(final String uuid) {
|
||||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||||
|
3
babel.config.js
Normal file
3
babel.config.js
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
presets: ['module:@react-native/babel-preset'],
|
||||||
|
};
|
@@ -16,7 +16,6 @@ static NSString *const paramLastVersion = @"lastVersion";
|
|||||||
static NSString *const paramCurrentVersion = @"currentVersion";
|
static NSString *const paramCurrentVersion = @"currentVersion";
|
||||||
static NSString *const paramIsFirstTime = @"isFirstTime";
|
static NSString *const paramIsFirstTime = @"isFirstTime";
|
||||||
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
|
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
|
||||||
static NSString *const keyBlockUpdate = @"REACTNATIVECN_PUSHY_BLOCKUPDATE";
|
|
||||||
static NSString *const keyUuid = @"REACTNATIVECN_PUSHY_UUID";
|
static NSString *const keyUuid = @"REACTNATIVECN_PUSHY_UUID";
|
||||||
static NSString *const keyHashInfo = @"REACTNATIVECN_PUSHY_HASH_";
|
static NSString *const keyHashInfo = @"REACTNATIVECN_PUSHY_HASH_";
|
||||||
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
|
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
|
||||||
@@ -157,7 +156,6 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
ret[@"buildTime"] = [RCTPushy buildTime];
|
ret[@"buildTime"] = [RCTPushy buildTime];
|
||||||
ret[@"rolledBackVersion"] = [defaults objectForKey:keyRolledBackMarked];
|
ret[@"rolledBackVersion"] = [defaults objectForKey:keyRolledBackMarked];
|
||||||
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
|
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
|
||||||
ret[@"blockUpdate"] = [defaults objectForKey:keyBlockUpdate];
|
|
||||||
ret[@"uuid"] = [defaults objectForKey:keyUuid];
|
ret[@"uuid"] = [defaults objectForKey:keyUuid];
|
||||||
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
|
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
|
||||||
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
|
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
|
||||||
@@ -192,24 +190,6 @@ RCT_EXPORT_MODULE(RCTPushy);
|
|||||||
return self;
|
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
|
RCT_EXPORT_METHOD(setUuid:(NSString *)uuid resolver:(RCTPromiseResolveBlock)resolve
|
||||||
rejecter:(RCTPromiseRejectBlock)reject)
|
rejecter:(RCTPromiseRejectBlock)reject)
|
||||||
{
|
{
|
||||||
|
25
package.json
25
package.json
@@ -1,10 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "react-native-update",
|
"name": "react-native-update",
|
||||||
"version": "10.0.0-beta.1",
|
"version": "10.4.0",
|
||||||
"description": "react-native hot update",
|
"description": "react-native hot update",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepublish": "yarn submodule",
|
"prepack": "yarn submodule && yarn lint",
|
||||||
|
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
|
||||||
"submodule": "git submodule update --init --recursive",
|
"submodule": "git submodule update --init --recursive",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"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",
|
"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",
|
||||||
@@ -40,32 +41,32 @@
|
|||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"react": ">=16.8.0",
|
"react": ">=16.8.0",
|
||||||
"react-native": ">=0.57.0"
|
"react-native": ">=0.59.0"
|
||||||
},
|
},
|
||||||
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.3"
|
"nanoid": "^3.3.3"
|
||||||
},
|
},
|
||||||
"codegenConfig": {
|
"codegenConfig": {
|
||||||
"libraries": [
|
"name": "RCTPushySpec",
|
||||||
{
|
"type": "modules",
|
||||||
"name": "RCTPushySpec",
|
"jsSrcsDir": "src"
|
||||||
"type": "modules",
|
|
||||||
"jsSrcsDir": "lib"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@babel/core": "^7.24.0",
|
||||||
|
"@react-native/babel-preset": "^0.73.21",
|
||||||
"@react-native/eslint-config": "^0.73.2",
|
"@react-native/eslint-config": "^0.73.2",
|
||||||
|
"@react-native/typescript-config": "^0.74.0",
|
||||||
"@types/fs-extra": "^9.0.13",
|
"@types/fs-extra": "^9.0.13",
|
||||||
"@types/jest": "^29.2.1",
|
"@types/jest": "^29.2.1",
|
||||||
"@types/node": "^20.8.9",
|
"@types/node": "^20.8.9",
|
||||||
"@types/react": "^18.2.46",
|
"@types/react": "^18.2.46",
|
||||||
"detox": "^20.5.0",
|
"detox": "^20.5.0",
|
||||||
"eslint": "^8.56.0",
|
"eslint": "^8.57.0",
|
||||||
|
"eslint-plugin-ft-flow": "^3.0.7",
|
||||||
"firebase-tools": "^11.24.1",
|
"firebase-tools": "^11.24.1",
|
||||||
"fs-extra": "^9.1.0",
|
"fs-extra": "^9.1.0",
|
||||||
"jest": "^29.2.1",
|
"jest": "^29.7.0",
|
||||||
"pod-install": "^0.1.37",
|
"pod-install": "^0.1.37",
|
||||||
"prettier": "^2",
|
"prettier": "^2",
|
||||||
"react": "18.2.0",
|
"react": "18.2.0",
|
||||||
|
@@ -1,5 +1,4 @@
|
|||||||
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
|
import { TurboModule, TurboModuleRegistry } from 'react-native';
|
||||||
import { TurboModuleRegistry } from 'react-native';
|
|
||||||
|
|
||||||
export interface Spec extends TurboModule {
|
export interface Spec extends TurboModule {
|
||||||
getConstants: () => {
|
getConstants: () => {
|
177
src/client.tsx
177
src/client.tsx
@@ -1,5 +1,5 @@
|
|||||||
import { CheckResult, PushyOptions, ProgressData } from './type';
|
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
|
||||||
import { assertRelease, log } from './utils';
|
import { log, testUrls } 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,19 +25,23 @@ 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;
|
||||||
lastResult: CheckResult;
|
lastRespJson?: Promise<any>;
|
||||||
|
|
||||||
progressHandlers: Record<string, EmitterSubscription> = {};
|
progressHandlers: Record<string, EmitterSubscription> = {};
|
||||||
downloadedHash: string;
|
downloadedHash?: string;
|
||||||
|
|
||||||
marked = false;
|
marked = false;
|
||||||
applyingUpdate = false;
|
applyingUpdate = false;
|
||||||
@@ -53,11 +57,47 @@ export class Pushy {
|
|||||||
setOptions = (options: Partial<PushyOptions>) => {
|
setOptions = (options: Partial<PushyOptions>) => {
|
||||||
for (const [key, value] of Object.entries(options)) {
|
for (const [key, value] of Object.entries(options)) {
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
|
// @ts-expect-error
|
||||||
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}`;
|
||||||
};
|
};
|
||||||
@@ -72,16 +112,20 @@ export class Pushy {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
markSuccess = () => {
|
markSuccess = () => {
|
||||||
assertRelease();
|
if (this.marked || __DEV__) {
|
||||||
if (this.marked) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.marked = true;
|
this.marked = true;
|
||||||
PushyModule.markSuccess();
|
PushyModule.markSuccess();
|
||||||
report({ type: 'markSuccess' });
|
this.report({ type: 'markSuccess' });
|
||||||
};
|
};
|
||||||
switchVersion = (hash: string) => {
|
switchVersion = (hash: string) => {
|
||||||
assertRelease();
|
if (__DEV__) {
|
||||||
|
console.warn(
|
||||||
|
'您调用了switchVersion方法,但是当前是开发环境,不会进行任何操作。',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (this.assertHash(hash) && !this.applyingUpdate) {
|
if (this.assertHash(hash) && !this.applyingUpdate) {
|
||||||
log('switchVersion: ' + hash);
|
log('switchVersion: ' + hash);
|
||||||
this.applyingUpdate = true;
|
this.applyingUpdate = true;
|
||||||
@@ -90,42 +134,50 @@ export class Pushy {
|
|||||||
};
|
};
|
||||||
|
|
||||||
switchVersionLater = (hash: string) => {
|
switchVersionLater = (hash: string) => {
|
||||||
assertRelease();
|
if (__DEV__) {
|
||||||
|
console.warn(
|
||||||
|
'您调用了switchVersionLater方法,但是当前是开发环境,不会进行任何操作。',
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (this.assertHash(hash)) {
|
if (this.assertHash(hash)) {
|
||||||
log('switchVersionLater: ' + hash);
|
log('switchVersionLater: ' + hash);
|
||||||
PushyModule.setNeedUpdate({ hash });
|
PushyModule.setNeedUpdate({ hash });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
checkUpdate = async () => {
|
checkUpdate = async () => {
|
||||||
assertRelease();
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (
|
if (
|
||||||
this.lastResult &&
|
this.lastRespJson &&
|
||||||
this.lastChecking &&
|
this.lastChecking &&
|
||||||
now - this.lastChecking < 1000 * 5
|
now - this.lastChecking < 1000 * 5
|
||||||
) {
|
) {
|
||||||
return this.lastResult;
|
return await this.lastRespJson;
|
||||||
}
|
}
|
||||||
this.lastChecking = now;
|
this.lastChecking = now;
|
||||||
report({ type: 'checking' });
|
this.report({ type: 'checking' });
|
||||||
|
const fetchBody = {
|
||||||
|
packageVersion,
|
||||||
|
hash: currentVersion,
|
||||||
|
buildTime,
|
||||||
|
cInfo,
|
||||||
|
};
|
||||||
|
if (__DEV__) {
|
||||||
|
delete fetchBody.buildTime;
|
||||||
|
}
|
||||||
const fetchPayload = {
|
const fetchPayload = {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
Accept: 'application/json',
|
Accept: 'application/json',
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(fetchBody),
|
||||||
packageVersion,
|
|
||||||
hash: currentVersion,
|
|
||||||
buildTime,
|
|
||||||
cInfo,
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
let resp;
|
let resp;
|
||||||
try {
|
try {
|
||||||
resp = await fetch(this.getCheckUrl(), fetchPayload);
|
resp = await fetch(this.getCheckUrl(), fetchPayload);
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
report({
|
this.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.',
|
||||||
});
|
});
|
||||||
@@ -133,7 +185,7 @@ export class Pushy {
|
|||||||
if (backupEndpoints) {
|
if (backupEndpoints) {
|
||||||
try {
|
try {
|
||||||
resp = await Promise.race(
|
resp = await Promise.race(
|
||||||
backupEndpoints.map((endpoint) =>
|
backupEndpoints.map(endpoint =>
|
||||||
fetch(this.getCheckUrl(endpoint), fetchPayload),
|
fetch(this.getCheckUrl(endpoint), fetchPayload),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -141,20 +193,19 @@ export class Pushy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!resp) {
|
if (!resp) {
|
||||||
report({
|
this.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.lastResult || empty;
|
return this.lastRespJson ? await this.lastRespJson : empty;
|
||||||
}
|
}
|
||||||
const result: CheckResult = await resp.json();
|
this.lastRespJson = resp.json();
|
||||||
|
|
||||||
this.lastResult = result;
|
const result: CheckResult = await this.lastRespJson;
|
||||||
|
|
||||||
if (resp.status !== 200) {
|
if (resp.status !== 200) {
|
||||||
report({
|
this.report({
|
||||||
type: 'errorChecking',
|
type: 'errorChecking',
|
||||||
//@ts-ignore
|
|
||||||
message: result.message,
|
message: result.message,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -176,7 +227,7 @@ export class Pushy {
|
|||||||
new Set([...(server.backups || []), ...remoteEndpoints]),
|
new Set([...(server.backups || []), ...remoteEndpoints]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
log('failed to fetch endpoints from: ', server.queryUrl);
|
log('failed to fetch endpoints from: ', server.queryUrl);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,12 +237,21 @@ export class Pushy {
|
|||||||
info: CheckResult,
|
info: CheckResult,
|
||||||
onDownloadProgress?: (data: ProgressData) => void,
|
onDownloadProgress?: (data: ProgressData) => void,
|
||||||
) => {
|
) => {
|
||||||
assertRelease();
|
const {
|
||||||
if (!('update' in info)) {
|
hash,
|
||||||
|
diffUrl: _diffUrl,
|
||||||
|
diffUrls,
|
||||||
|
pdiffUrl: _pdiffUrl,
|
||||||
|
pdiffUrls,
|
||||||
|
updateUrl: _updateUrl,
|
||||||
|
updateUrls,
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
metaInfo,
|
||||||
|
} = info;
|
||||||
|
if (!info.update || !hash) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
|
|
||||||
info;
|
|
||||||
if (rolledBackVersion === hash) {
|
if (rolledBackVersion === hash) {
|
||||||
log(`rolledback hash ${rolledBackVersion}, ignored`);
|
log(`rolledback hash ${rolledBackVersion}, ignored`);
|
||||||
return;
|
return;
|
||||||
@@ -206,7 +266,7 @@ export class Pushy {
|
|||||||
if (onDownloadProgress) {
|
if (onDownloadProgress) {
|
||||||
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
|
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
|
||||||
'RCTPushyDownloadProgress',
|
'RCTPushyDownloadProgress',
|
||||||
(progressData) => {
|
progressData => {
|
||||||
if (progressData.hash === hash) {
|
if (progressData.hash === hash) {
|
||||||
onDownloadProgress(progressData);
|
onDownloadProgress(progressData);
|
||||||
}
|
}
|
||||||
@@ -214,7 +274,8 @@ export class Pushy {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
let succeeded = false;
|
let succeeded = false;
|
||||||
report({ type: 'downloading' });
|
this.report({ type: 'downloading' });
|
||||||
|
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
|
||||||
if (diffUrl) {
|
if (diffUrl) {
|
||||||
log('downloading diff');
|
log('downloading diff');
|
||||||
try {
|
try {
|
||||||
@@ -224,10 +285,15 @@ export class Pushy {
|
|||||||
originHash: currentVersion,
|
originHash: currentVersion,
|
||||||
});
|
});
|
||||||
succeeded = true;
|
succeeded = true;
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
log(`diff error: ${e.message}, try pdiff`);
|
if (__DEV__) {
|
||||||
|
succeeded = true;
|
||||||
|
} else {
|
||||||
|
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 {
|
||||||
@@ -236,10 +302,15 @@ export class Pushy {
|
|||||||
hash,
|
hash,
|
||||||
});
|
});
|
||||||
succeeded = true;
|
succeeded = true;
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
log(`pdiff error: ${e.message}, try full patch`);
|
if (__DEV__) {
|
||||||
|
succeeded = true;
|
||||||
|
} else {
|
||||||
|
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 {
|
||||||
@@ -248,20 +319,28 @@ export class Pushy {
|
|||||||
hash,
|
hash,
|
||||||
});
|
});
|
||||||
succeeded = true;
|
succeeded = true;
|
||||||
} catch (e) {
|
} catch (e: any) {
|
||||||
log(`full patch error: ${e.message}`);
|
if (__DEV__) {
|
||||||
|
succeeded = true;
|
||||||
|
} else {
|
||||||
|
log(`full patch error: ${e.message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.progressHandlers[hash]) {
|
if (this.progressHandlers[hash]) {
|
||||||
this.progressHandlers[hash].remove();
|
this.progressHandlers[hash].remove();
|
||||||
delete this.progressHandlers[hash];
|
delete this.progressHandlers[hash];
|
||||||
}
|
}
|
||||||
|
if (__DEV__) {
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
if (!succeeded) {
|
if (!succeeded) {
|
||||||
return report({
|
return this.report({
|
||||||
type: 'errorUpdate',
|
type: 'errorUpdate',
|
||||||
data: { newVersion: hash },
|
data: { newVersion: hash },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
log('downloaded hash:', hash);
|
||||||
setLocalHashInfo(hash, {
|
setLocalHashInfo(hash, {
|
||||||
name,
|
name,
|
||||||
description,
|
description,
|
||||||
@@ -277,17 +356,17 @@ export class Pushy {
|
|||||||
if (Platform.OS !== 'android') {
|
if (Platform.OS !== 'android') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
report({ type: 'downloadingApk' });
|
this.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 report({ type: 'rejectStoragePermission' });
|
return this.report({ type: 'rejectStoragePermission' });
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (e: any) {
|
||||||
return report({ type: 'errorStoragePermission' });
|
return this.report({ type: 'errorStoragePermission' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const progressKey = 'downloadingApk';
|
const progressKey = 'downloadingApk';
|
||||||
@@ -306,7 +385,7 @@ export class Pushy {
|
|||||||
target: 'update.apk',
|
target: 'update.apk',
|
||||||
hash: progressKey,
|
hash: progressKey,
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
report({ type: 'errowDownloadAndInstallApk' });
|
this.report({ type: 'errowDownloadAndInstallApk' });
|
||||||
});
|
});
|
||||||
if (this.progressHandlers[progressKey]) {
|
if (this.progressHandlers[progressKey]) {
|
||||||
this.progressHandlers[progressKey].remove();
|
this.progressHandlers[progressKey].remove();
|
||||||
|
13
src/client.web.js
Normal file
13
src/client.web.js
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
const noop = () => {};
|
||||||
|
export class Pushy {
|
||||||
|
constructor() {
|
||||||
|
console.warn(
|
||||||
|
'react-native-update is not supported and will do nothing on web.',
|
||||||
|
);
|
||||||
|
return new Proxy(this, {
|
||||||
|
get() {
|
||||||
|
return noop;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@@ -2,27 +2,35 @@ 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: () => Promise.resolve(empty),
|
checkUpdate: asyncNoop,
|
||||||
switchVersion: noop,
|
switchVersion: noop,
|
||||||
switchVersionLater: noop,
|
switchVersionLater: noop,
|
||||||
markSuccess: noop,
|
markSuccess: noop,
|
||||||
dismissError: noop,
|
dismissError: noop,
|
||||||
downloadUpdate: noop,
|
downloadUpdate: asyncNoop,
|
||||||
|
downloadAndInstallApk: asyncNoop,
|
||||||
|
getCurrentVersionInfo: () => Promise.resolve({}),
|
||||||
currentHash: '',
|
currentHash: '',
|
||||||
packageVersion: '',
|
packageVersion: '',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PushyContext = createContext<{
|
export const PushyContext = createContext<{
|
||||||
checkUpdate: () => void;
|
checkUpdate: () => Promise<void>;
|
||||||
switchVersion: () => void;
|
switchVersion: () => void;
|
||||||
switchVersionLater: () => void;
|
switchVersionLater: () => void;
|
||||||
markSuccess: () => void;
|
markSuccess: () => void;
|
||||||
dismissError: () => void;
|
dismissError: () => void;
|
||||||
downloadUpdate: () => void;
|
downloadUpdate: () => Promise<void>;
|
||||||
|
downloadAndInstallApk: (url: string) => Promise<void>;
|
||||||
|
getCurrentVersionInfo: () => Promise<{
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
metaInfo?: string;
|
||||||
|
}>;
|
||||||
currentHash: string;
|
currentHash: string;
|
||||||
packageVersion: string;
|
packageVersion: string;
|
||||||
client?: Pushy;
|
client?: Pushy;
|
||||||
|
45
src/core.ts
45
src/core.ts
@@ -1,14 +1,15 @@
|
|||||||
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,
|
||||||
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||||
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
||||||
const isTurboModuleEnabled = global.__turboModuleProxy != null;
|
const isTurboModuleEnabled =
|
||||||
|
// @ts-expect-error
|
||||||
|
global.__turboModuleProxy != null;
|
||||||
|
|
||||||
export const PushyModule = isTurboModuleEnabled
|
export const PushyModule = isTurboModuleEnabled
|
||||||
? require('./turboModuleSpec').default
|
? require('./NativePushy').default
|
||||||
: NativeModules.Pushy;
|
: NativeModules.Pushy;
|
||||||
|
|
||||||
if (!PushyModule) {
|
if (!PushyModule) {
|
||||||
@@ -58,44 +59,6 @@ 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 = {
|
||||||
|
@@ -1,17 +0,0 @@
|
|||||||
import { Fragment } from 'react';
|
|
||||||
|
|
||||||
const noop = () => {};
|
|
||||||
export class Pushy {
|
|
||||||
constructor() {
|
|
||||||
console.warn('react-native-update is not supported and will do nothing on web.');
|
|
||||||
return new Proxy(this, {
|
|
||||||
get() {
|
|
||||||
return noop;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export { PushyContext, usePushy } from './context';
|
|
||||||
|
|
||||||
export const PushyProvider = Fragment;
|
|
148
src/provider.tsx
148
src/provider.tsx
@@ -13,8 +13,13 @@ import {
|
|||||||
Linking,
|
Linking,
|
||||||
} from 'react-native';
|
} from 'react-native';
|
||||||
import { Pushy } from './client';
|
import { Pushy } from './client';
|
||||||
import { currentVersion, isFirstTime, packageVersion } from './core';
|
import {
|
||||||
import { CheckResult } from './type';
|
currentVersion,
|
||||||
|
isFirstTime,
|
||||||
|
packageVersion,
|
||||||
|
getCurrentVersionInfo,
|
||||||
|
} from './core';
|
||||||
|
import { CheckResult, ProgressData } from './type';
|
||||||
import { PushyContext } from './context';
|
import { PushyContext } from './context';
|
||||||
|
|
||||||
export const PushyProvider = ({
|
export const PushyProvider = ({
|
||||||
@@ -24,97 +29,116 @@ export const PushyProvider = ({
|
|||||||
client: Pushy;
|
client: Pushy;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) => {
|
}) => {
|
||||||
const { strategy, useAlert } = client.options;
|
const { options } = client;
|
||||||
const stateListener = useRef<NativeEventSubscription>();
|
const stateListener = useRef<NativeEventSubscription>();
|
||||||
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
|
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
|
||||||
|
const updateInfoRef = useRef(updateInfo);
|
||||||
|
const [progress, setProgress] = useState<ProgressData>();
|
||||||
const [lastError, setLastError] = useState<Error>();
|
const [lastError, setLastError] = useState<Error>();
|
||||||
|
const lastChecking = useRef(0);
|
||||||
|
|
||||||
const dismissError = useCallback(() => {
|
const dismissError = useCallback(() => {
|
||||||
if (lastError) {
|
setLastError(undefined);
|
||||||
setLastError(undefined);
|
}, []);
|
||||||
}
|
|
||||||
}, [lastError]);
|
|
||||||
|
|
||||||
const showAlert = useCallback(
|
const showAlert = useCallback(
|
||||||
(...args: Parameters<typeof Alert.alert>) => {
|
(...args: Parameters<typeof Alert.alert>) => {
|
||||||
if (useAlert) {
|
if (options.useAlert) {
|
||||||
Alert.alert(...args);
|
Alert.alert(...args);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[useAlert],
|
[options],
|
||||||
);
|
);
|
||||||
|
|
||||||
const switchVersion = useCallback(() => {
|
const switchVersion = useCallback(() => {
|
||||||
if (updateInfo && 'hash' in updateInfo) {
|
if (updateInfo && updateInfo.hash) {
|
||||||
client.switchVersion(updateInfo.hash);
|
client.switchVersion(updateInfo.hash);
|
||||||
}
|
}
|
||||||
}, [client, updateInfo]);
|
}, [client, updateInfo]);
|
||||||
|
|
||||||
const switchVersionLater = useCallback(() => {
|
const switchVersionLater = useCallback(() => {
|
||||||
if (updateInfo && 'hash' in updateInfo) {
|
if (updateInfo && updateInfo.hash) {
|
||||||
client.switchVersionLater(updateInfo.hash);
|
client.switchVersionLater(updateInfo.hash);
|
||||||
}
|
}
|
||||||
}, [client, updateInfo]);
|
}, [client, updateInfo]);
|
||||||
|
|
||||||
const downloadUpdate = useCallback(async () => {
|
const downloadUpdate = useCallback(
|
||||||
if (!updateInfo || !('update' in updateInfo)) {
|
async (info: CheckResult | undefined = updateInfoRef.current) => {
|
||||||
return;
|
if (!info || !info.update) {
|
||||||
}
|
|
||||||
try {
|
|
||||||
const hash = await client.downloadUpdate(updateInfo);
|
|
||||||
if (!hash) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
stateListener.current && stateListener.current.remove();
|
try {
|
||||||
showAlert('提示', '下载完毕,是否立即更新?', [
|
const hash = await client.downloadUpdate(info, setProgress);
|
||||||
{
|
if (!hash) {
|
||||||
text: '下次再说',
|
return;
|
||||||
style: 'cancel',
|
}
|
||||||
onPress: () => {
|
stateListener.current && stateListener.current.remove();
|
||||||
client.switchVersionLater(hash);
|
showAlert('提示', '下载完毕,是否立即更新?', [
|
||||||
|
{
|
||||||
|
text: '下次再说',
|
||||||
|
style: 'cancel',
|
||||||
|
onPress: () => {
|
||||||
|
client.switchVersionLater(hash);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
text: '立即更新',
|
||||||
text: '立即更新',
|
style: 'default',
|
||||||
style: 'default',
|
onPress: () => {
|
||||||
onPress: () => {
|
client.switchVersion(hash);
|
||||||
client.switchVersion(hash);
|
},
|
||||||
},
|
},
|
||||||
},
|
]);
|
||||||
]);
|
} catch (e: any) {
|
||||||
} catch (err) {
|
setLastError(e);
|
||||||
setLastError(err);
|
showAlert('更新失败', e.message);
|
||||||
showAlert('更新失败', err.message);
|
}
|
||||||
}
|
},
|
||||||
}, [client, showAlert, updateInfo]);
|
[client, showAlert],
|
||||||
|
);
|
||||||
|
|
||||||
|
const downloadAndInstallApk = useCallback(
|
||||||
|
async (downloadUrl: string) => {
|
||||||
|
if (Platform.OS === 'android' && downloadUrl) {
|
||||||
|
await client.downloadAndInstallApk(downloadUrl, setProgress);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[client],
|
||||||
|
);
|
||||||
|
|
||||||
const checkUpdate = useCallback(async () => {
|
const checkUpdate = useCallback(async () => {
|
||||||
|
const now = Date.now();
|
||||||
|
if (lastChecking.current && now - lastChecking.current < 1000) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastChecking.current = now;
|
||||||
let info: CheckResult;
|
let info: CheckResult;
|
||||||
try {
|
try {
|
||||||
info = await client.checkUpdate();
|
info = await client.checkUpdate();
|
||||||
} catch (err) {
|
} catch (e: any) {
|
||||||
setLastError(err);
|
setLastError(e);
|
||||||
showAlert('更新检查失败', err.message);
|
showAlert('更新检查失败', e.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
updateInfoRef.current = info;
|
||||||
setUpdateInfo(info);
|
setUpdateInfo(info);
|
||||||
if ('expired' in info) {
|
if (info.expired) {
|
||||||
const { downloadUrl } = info;
|
const { downloadUrl } = info;
|
||||||
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
if (downloadUrl) {
|
||||||
{
|
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||||
text: '更新',
|
{
|
||||||
onPress: () => {
|
text: '更新',
|
||||||
if (downloadUrl) {
|
onPress: () => {
|
||||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||||
client.downloadAndInstallApk(downloadUrl);
|
downloadAndInstallApk(downloadUrl);
|
||||||
} else {
|
} else {
|
||||||
Linking.openURL(downloadUrl);
|
Linking.openURL(downloadUrl);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
},
|
]);
|
||||||
]);
|
}
|
||||||
} else if ('update' in info) {
|
} else if (info.update) {
|
||||||
showAlert(
|
showAlert(
|
||||||
'提示',
|
'提示',
|
||||||
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
|
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
|
||||||
@@ -130,18 +154,23 @@ export const PushyProvider = ({
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}, [client, downloadUpdate, showAlert]);
|
}, [client, downloadAndInstallApk, downloadUpdate, showAlert]);
|
||||||
|
|
||||||
const markSuccess = client.markSuccess;
|
const markSuccess = client.markSuccess;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isFirstTime) {
|
if (__DEV__) {
|
||||||
|
console.info('检测到在DEV环境,不会进行热更新检查');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||||
|
if (isFirstTime && autoMarkSuccess) {
|
||||||
markSuccess();
|
markSuccess();
|
||||||
}
|
}
|
||||||
if (strategy === 'both' || strategy === 'onAppResume') {
|
if (strategy === 'both' || strategy === 'onAppResume') {
|
||||||
stateListener.current = AppState.addEventListener(
|
stateListener.current = AppState.addEventListener(
|
||||||
'change',
|
'change',
|
||||||
(nextAppState) => {
|
nextAppState => {
|
||||||
if (nextAppState === 'active') {
|
if (nextAppState === 'active') {
|
||||||
checkUpdate();
|
checkUpdate();
|
||||||
}
|
}
|
||||||
@@ -152,7 +181,6 @@ 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();
|
||||||
@@ -162,7 +190,7 @@ export const PushyProvider = ({
|
|||||||
stateListener.current && stateListener.current.remove();
|
stateListener.current && stateListener.current.remove();
|
||||||
clearTimeout(dismissErrorTimer);
|
clearTimeout(dismissErrorTimer);
|
||||||
};
|
};
|
||||||
}, [checkUpdate, client.options, dismissError, markSuccess, strategy]);
|
}, [checkUpdate, options, dismissError, markSuccess]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PushyContext.Provider
|
<PushyContext.Provider
|
||||||
@@ -178,8 +206,10 @@ export const PushyProvider = ({
|
|||||||
downloadUpdate,
|
downloadUpdate,
|
||||||
packageVersion,
|
packageVersion,
|
||||||
currentHash: currentVersion,
|
currentHash: currentVersion,
|
||||||
}}
|
progress,
|
||||||
>
|
downloadAndInstallApk,
|
||||||
|
getCurrentVersionInfo,
|
||||||
|
}}>
|
||||||
{children}
|
{children}
|
||||||
</PushyContext.Provider>
|
</PushyContext.Provider>
|
||||||
);
|
);
|
||||||
|
2
src/provider.web.js
Normal file
2
src/provider.web.js
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
import { Fragment } from 'react';
|
||||||
|
export const PushyProvider = Fragment;
|
43
src/type.ts
43
src/type.ts
@@ -1,31 +1,22 @@
|
|||||||
export interface ExpiredResult {
|
export interface CheckResult {
|
||||||
expired: true;
|
upToDate?: true;
|
||||||
downloadUrl: string;
|
expired?: true;
|
||||||
}
|
downloadUrl?: string;
|
||||||
|
update?: true;
|
||||||
export interface UpTodateResult {
|
name?: string; // version name
|
||||||
upToDate: true;
|
hash?: string;
|
||||||
paused?: 'app' | 'package';
|
description?: string;
|
||||||
}
|
metaInfo?: string;
|
||||||
|
pdiffUrl?: string;
|
||||||
export interface UpdateAvailableResult {
|
pdiffUrls?: string[];
|
||||||
upToDate: false;
|
|
||||||
update: true;
|
|
||||||
name: string; // version name
|
|
||||||
hash: string;
|
|
||||||
description: string;
|
|
||||||
metaInfo: string;
|
|
||||||
pdiffUrl: string;
|
|
||||||
diffUrl?: string;
|
diffUrl?: string;
|
||||||
|
diffUrls?: string[];
|
||||||
updateUrl?: string;
|
updateUrl?: string;
|
||||||
|
updateUrls?: string[];
|
||||||
|
paused?: 'app' | 'package';
|
||||||
|
message?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CheckResult =
|
|
||||||
| ExpiredResult
|
|
||||||
| UpTodateResult
|
|
||||||
| UpdateAvailableResult
|
|
||||||
| {};
|
|
||||||
|
|
||||||
export interface ProgressData {
|
export interface ProgressData {
|
||||||
hash: string;
|
hash: string;
|
||||||
received: number;
|
received: number;
|
||||||
@@ -59,6 +50,7 @@ export interface EventData {
|
|||||||
newVersion?: string;
|
newVersion?: string;
|
||||||
[key: string]: any;
|
[key: string]: any;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UpdateEventsLogger = ({
|
export type UpdateEventsLogger = ({
|
||||||
type,
|
type,
|
||||||
data,
|
data,
|
||||||
@@ -72,12 +64,13 @@ export interface PushyServerConfig {
|
|||||||
backups?: string[];
|
backups?: string[];
|
||||||
queryUrl?: string;
|
queryUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PushyOptions {
|
export interface PushyOptions {
|
||||||
appKey: string;
|
appKey: string;
|
||||||
server?: PushyServerConfig;
|
server?: PushyServerConfig;
|
||||||
logger?: UpdateEventsLogger;
|
logger?: UpdateEventsLogger;
|
||||||
useAlert?: boolean;
|
useAlert?: boolean;
|
||||||
strategy?: 'onAppStart' | 'onAppResume' | 'both';
|
strategy?: 'onAppStart' | 'onAppResume' | 'both' | null;
|
||||||
autoMarkSuccess?: boolean;
|
autoMarkSuccess?: boolean;
|
||||||
dismissErrorAfter?: number;
|
dismissErrorAfter?: number;
|
||||||
}
|
}
|
||||||
|
21
src/utils.ts
21
src/utils.ts
@@ -2,8 +2,21 @@ export function log(...args: any[]) {
|
|||||||
console.log('pushy: ', ...args);
|
console.log('pushy: ', ...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assertRelease() {
|
const ping = async (url: string) =>
|
||||||
if (__DEV__) {
|
Promise.race([
|
||||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
fetch(url, {
|
||||||
|
method: 'HEAD',
|
||||||
|
}).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,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
6
tea.yaml
Normal file
6
tea.yaml
Normal 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
4
tsconfig.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "@react-native/typescript-config/tsconfig.json",
|
||||||
|
"include": ["src/**/*"]
|
||||||
|
}
|
Reference in New Issue
Block a user