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

...

46 Commits

Author SHA1 Message Date
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
32 changed files with 941 additions and 679 deletions

View File

@@ -1,4 +0,0 @@
{
"root": true,
"extends": "@react-native"
}

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

@@ -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

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

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

@@ -33,10 +33,8 @@ function App() {
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
const snackbarVisible =
showUpdateSnackbar &&
updateInfo &&
updateInfo.updateAvailable &&
!useDefaultAlert;
!useDefaultAlert && showUpdateSnackbar && updateInfo?.update;
return (
<View style={styles.container}>
<Text style={styles.welcome}>使Pushy热更新服务</Text>
@@ -48,9 +46,10 @@ function App() {
value={useDefaultAlert}
onValueChange={v => {
setUseDefaultAlert(v);
client.setOptions({
showAlert: v,
client?.setOptions({
useAlert: v,
});
setShowUpdateSnackbar(!v);
}}
/>
</View>
@@ -69,7 +68,11 @@ function App() {
<Text>
{received} / {total}
</Text>
<TouchableOpacity onPress={checkUpdate}>
<TouchableOpacity
onPress={() => {
checkUpdate();
setShowUpdateSnackbar(true);
}}>
<Text style={styles.instructions}></Text>
</TouchableOpacity>
@@ -80,13 +83,13 @@ function App() {
setShowTestConsole(true);
}}>
<Text style={styles.instructions}>
react-native-update版本{client.version}
react-native-update版本{client?.version}
</Text>
</TouchableOpacity>
<TestConsole visible={showTestConsole} />
{snackbarVisible && (
<Snackbar
visible={true}
visible={snackbarVisible}
onDismiss={() => {
setShowUpdateSnackbar(false);
}}
@@ -98,10 +101,13 @@ function App() {
setShowUpdateBanner(true);
},
}}>
<Text>({updateInfo.version})</Text>
<Text style={{color: 'white'}}>
({updateInfo.name})
</Text>
</Snackbar>
)}
<Banner
style={{width: '100%', position: 'absolute', top: 0}}
visible={showUpdateBanner}
actions={[
{
@@ -147,7 +153,6 @@ const styles = StyleSheet.create({
const pushyClient = new Pushy({
appKey,
showAlert: false,
});
export default function Root() {

View File

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

View File

@@ -6231,10 +6231,10 @@ react-native-safe-area-context@^4.8.2:
resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65"
integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ==
react-native-update@10.0.0-beta.1:
version "10.0.0-beta.1"
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.0-beta.1.tgz#bc49a7197dd19c16ba798ea13324b4b292edd052"
integrity sha512-PFTsut8SL+vqAPtBUzPg9KKU9mFgCktKttifzM8B4puSoburlSN2UnD+eDWxLkXyIWQtoQAqAmXPE1/zA/e7dw==
react-native-update@^10.2.6:
version "10.2.6"
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"

View File

@@ -166,13 +166,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) {
@@ -108,11 +108,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

@@ -239,18 +239,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

@@ -192,24 +192,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,10 +1,11 @@
{
"name": "react-native-update",
"version": "10.0.0-beta.1",
"version": "10.3.0",
"description": "react-native hot update",
"main": "src/index.ts",
"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",
@@ -47,25 +48,25 @@
"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.56.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",

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: () => {

View File

@@ -1,5 +1,5 @@
import { CheckResult, PushyOptions, ProgressData } from './type';
import { assertRelease, log } from './utils';
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { assertRelease, log, testUrls } from './utils';
import {
EmitterSubscription,
PermissionsAndroid,
@@ -12,9 +12,9 @@ import {
pushyNativeEventEmitter,
currentVersion,
packageVersion,
report,
rolledBackVersion,
setLocalHashInfo,
isRolledBack,
} from './core';
const defaultServer = {
@@ -25,19 +25,23 @@ const defaultServer = {
};
const empty = {};
const noop = () => {};
export class Pushy {
options: PushyOptions = {
appKey: '',
server: defaultServer,
autoMarkSuccess: true,
useAlert: true,
strategy: 'both',
logger: noop,
};
lastChecking: number;
lastResult: CheckResult;
lastChecking?: number;
lastRespJson?: Promise<any>;
progressHandlers: Record<string, EmitterSubscription> = {};
downloadedHash: string;
downloadedHash?: string;
marked = false;
applyingUpdate = false;
@@ -53,11 +57,47 @@ export class Pushy {
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}`;
};
@@ -78,7 +118,7 @@ export class Pushy {
}
this.marked = true;
PushyModule.markSuccess();
report({ type: 'markSuccess' });
this.report({ type: 'markSuccess' });
};
switchVersion = (hash: string) => {
assertRelease();
@@ -100,14 +140,14 @@ export class Pushy {
assertRelease();
const now = Date.now();
if (
this.lastResult &&
this.lastRespJson &&
this.lastChecking &&
now - this.lastChecking < 1000 * 5
) {
return this.lastResult;
return await this.lastRespJson;
}
this.lastChecking = now;
report({ type: 'checking' });
this.report({ type: 'checking' });
const fetchPayload = {
method: 'POST',
headers: {
@@ -124,8 +164,8 @@ export class Pushy {
let resp;
try {
resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e) {
report({
} catch (e: any) {
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Trying backup endpoints.',
});
@@ -133,7 +173,7 @@ export class Pushy {
if (backupEndpoints) {
try {
resp = await Promise.race(
backupEndpoints.map((endpoint) =>
backupEndpoints.map(endpoint =>
fetch(this.getCheckUrl(endpoint), fetchPayload),
),
);
@@ -141,20 +181,19 @@ export class Pushy {
}
}
if (!resp) {
report({
this.report({
type: 'errorChecking',
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) {
report({
this.report({
type: 'errorChecking',
//@ts-ignore
message: result.message,
});
}
@@ -176,7 +215,7 @@ export class Pushy {
new Set([...(server.backups || []), ...remoteEndpoints]),
);
}
} catch (e) {
} catch (e: any) {
log('failed to fetch endpoints from: ', server.queryUrl);
}
}
@@ -187,11 +226,21 @@ export class Pushy {
onDownloadProgress?: (data: ProgressData) => void,
) => {
assertRelease();
if (!('update' in info)) {
const {
hash,
diffUrl: _diffUrl,
diffUrls,
pdiffUrl: _pdiffUrl,
pdiffUrls,
updateUrl: _updateUrl,
updateUrls,
name,
description,
metaInfo,
} = info;
if (!info.update || !hash) {
return;
}
const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
info;
if (rolledBackVersion === hash) {
log(`rolledback hash ${rolledBackVersion}, ignored`);
return;
@@ -206,7 +255,7 @@ export class Pushy {
if (onDownloadProgress) {
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
progressData => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
@@ -214,7 +263,8 @@ export class Pushy {
);
}
let succeeded = false;
report({ type: 'downloading' });
this.report({ type: 'downloading' });
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
if (diffUrl) {
log('downloading diff');
try {
@@ -224,10 +274,11 @@ export class Pushy {
originHash: currentVersion,
});
succeeded = true;
} catch (e) {
} catch (e: any) {
log(`diff error: ${e.message}, try pdiff`);
}
}
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
if (!succeeded && pdiffUrl) {
log('downloading pdiff');
try {
@@ -236,10 +287,11 @@ export class Pushy {
hash,
});
succeeded = true;
} catch (e) {
} catch (e: any) {
log(`pdiff error: ${e.message}, try full patch`);
}
}
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
if (!succeeded && updateUrl) {
log('downloading full patch');
try {
@@ -248,7 +300,7 @@ export class Pushy {
hash,
});
succeeded = true;
} catch (e) {
} catch (e: any) {
log(`full patch error: ${e.message}`);
}
}
@@ -257,11 +309,12 @@ export class Pushy {
delete this.progressHandlers[hash];
}
if (!succeeded) {
return report({
return this.report({
type: 'errorUpdate',
data: { newVersion: hash },
});
}
log('downloaded hash:', hash);
setLocalHashInfo(hash, {
name,
description,
@@ -277,17 +330,17 @@ export class Pushy {
if (Platform.OS !== 'android') {
return;
}
report({ type: 'downloadingApk' });
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 report({ type: 'rejectStoragePermission' });
return this.report({ type: 'rejectStoragePermission' });
}
} catch (err) {
return report({ type: 'errorStoragePermission' });
} catch (e: any) {
return this.report({ type: 'errorStoragePermission' });
}
}
const progressKey = 'downloadingApk';
@@ -306,7 +359,7 @@ export class Pushy {
target: 'update.apk',
hash: progressKey,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
this.report({ type: 'errowDownloadAndInstallApk' });
});
if (this.progressHandlers[progressKey]) {
this.progressHandlers[progressKey].remove();

13
src/client.web.js Normal file
View 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;
},
});
}
}

View File

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

View File

@@ -1,14 +1,15 @@
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { EventType, UpdateEventsLogger } from './type';
import { log } from './utils';
const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
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
? require('./turboModuleSpec').default
? require('./NativePushy').default
: NativeModules.Pushy;
if (!PushyModule) {
@@ -58,44 +59,6 @@ if (!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);
export const cInfo = {

View File

@@ -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;

View File

@@ -13,8 +13,13 @@ import {
Linking,
} from 'react-native';
import { Pushy } from './client';
import { currentVersion, isFirstTime, packageVersion } from './core';
import { CheckResult } from './type';
import {
currentVersion,
isFirstTime,
packageVersion,
getCurrentVersionInfo,
} from './core';
import { CheckResult, ProgressData } from './type';
import { PushyContext } from './context';
export const PushyProvider = ({
@@ -24,81 +29,100 @@ export const PushyProvider = ({
client: Pushy;
children: ReactNode;
}) => {
const { strategy, useAlert } = client.options;
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(() => {
if (lastError) {
setLastError(undefined);
}
}, [lastError]);
setLastError(undefined);
}, []);
const showAlert = useCallback(
(...args: Parameters<typeof Alert.alert>) => {
if (useAlert) {
if (options.useAlert) {
Alert.alert(...args);
}
},
[useAlert],
[options],
);
const switchVersion = useCallback(() => {
if (updateInfo && 'hash' in updateInfo) {
if (updateInfo && updateInfo.hash) {
client.switchVersion(updateInfo.hash);
}
}, [client, updateInfo]);
const switchVersionLater = useCallback(() => {
if (updateInfo && 'hash' in updateInfo) {
if (updateInfo && updateInfo.hash) {
client.switchVersionLater(updateInfo.hash);
}
}, [client, updateInfo]);
const downloadUpdate = useCallback(async () => {
if (!updateInfo || !('update' in updateInfo)) {
return;
}
try {
const hash = await client.downloadUpdate(updateInfo);
if (!hash) {
const downloadUpdate = useCallback(
async (info: CheckResult | undefined = updateInfoRef.current) => {
if (!info || !info.update) {
return;
}
stateListener.current && stateListener.current.remove();
showAlert('提示', '下载完毕,是否立即更新?', [
{
text: '下次再说',
style: 'cancel',
onPress: () => {
client.switchVersionLater(hash);
try {
const hash = await client.downloadUpdate(info, setProgress);
if (!hash) {
return;
}
stateListener.current && stateListener.current.remove();
showAlert('提示', '下载完毕,是否立即更新?', [
{
text: '下次再说',
style: 'cancel',
onPress: () => {
client.switchVersionLater(hash);
},
},
},
{
text: '立即更新',
style: 'default',
onPress: () => {
client.switchVersion(hash);
{
text: '立即更新',
style: 'default',
onPress: () => {
client.switchVersion(hash);
},
},
},
]);
} catch (err) {
setLastError(err);
showAlert('更新失败', err.message);
}
}, [client, showAlert, updateInfo]);
]);
} catch (e: any) {
setLastError(e);
showAlert('更新失败', e.message);
}
},
[client, showAlert],
);
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 (err) {
setLastError(err);
showAlert('更新检查失败', err.message);
} catch (e: any) {
setLastError(e);
showAlert('更新检查失败', e.message);
return;
}
updateInfoRef.current = info;
setUpdateInfo(info);
if ('expired' in info) {
if (info.expired) {
const { downloadUrl } = info;
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
{
@@ -106,7 +130,7 @@ export const PushyProvider = ({
onPress: () => {
if (downloadUrl) {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
client.downloadAndInstallApk(downloadUrl);
downloadAndInstallApk(downloadUrl);
} else {
Linking.openURL(downloadUrl);
}
@@ -114,7 +138,7 @@ export const PushyProvider = ({
},
},
]);
} else if ('update' in info) {
} else if (info.update) {
showAlert(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
@@ -130,18 +154,23 @@ export const PushyProvider = ({
],
);
}
}, [client, downloadUpdate, showAlert]);
}, [client, downloadAndInstallApk, downloadUpdate, showAlert]);
const markSuccess = client.markSuccess;
useEffect(() => {
if (isFirstTime) {
if (__DEV__) {
console.info('检测到在DEV环境不会进行热更新检查');
return;
}
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
if (isFirstTime && autoMarkSuccess) {
markSuccess();
}
if (strategy === 'both' || strategy === 'onAppResume') {
stateListener.current = AppState.addEventListener(
'change',
(nextAppState) => {
nextAppState => {
if (nextAppState === 'active') {
checkUpdate();
}
@@ -152,7 +181,6 @@ export const PushyProvider = ({
checkUpdate();
}
let dismissErrorTimer: ReturnType<typeof setTimeout>;
const { dismissErrorAfter } = client.options;
if (typeof dismissErrorAfter === 'number' && dismissErrorAfter > 0) {
dismissErrorTimer = setTimeout(() => {
dismissError();
@@ -162,7 +190,7 @@ export const PushyProvider = ({
stateListener.current && stateListener.current.remove();
clearTimeout(dismissErrorTimer);
};
}, [checkUpdate, client.options, dismissError, markSuccess, strategy]);
}, [checkUpdate, options, dismissError, markSuccess]);
return (
<PushyContext.Provider
@@ -178,8 +206,10 @@ export const PushyProvider = ({
downloadUpdate,
packageVersion,
currentHash: currentVersion,
}}
>
progress,
downloadAndInstallApk,
getCurrentVersionInfo,
}}>
{children}
</PushyContext.Provider>
);

2
src/provider.web.js Normal file
View File

@@ -0,0 +1,2 @@
import { Fragment } from 'react';
export const PushyProvider = Fragment;

View File

@@ -1,31 +1,22 @@
export interface ExpiredResult {
expired: true;
downloadUrl: string;
}
export interface UpTodateResult {
upToDate: true;
paused?: 'app' | 'package';
}
export interface UpdateAvailableResult {
upToDate: false;
update: true;
name: string; // version name
hash: string;
description: string;
metaInfo: string;
pdiffUrl: string;
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 type CheckResult =
| ExpiredResult
| UpTodateResult
| UpdateAvailableResult
| {};
export interface ProgressData {
hash: string;
received: number;
@@ -59,6 +50,7 @@ export interface EventData {
newVersion?: string;
[key: string]: any;
}
export type UpdateEventsLogger = ({
type,
data,
@@ -72,6 +64,7 @@ export interface PushyServerConfig {
backups?: string[];
queryUrl?: string;
}
export interface PushyOptions {
appKey: string;
server?: PushyServerConfig;

View File

@@ -7,3 +7,22 @@ export function assertRelease() {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
const ping = async (url: string) =>
Promise.race([
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
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/**/*"]
}

924
yarn.lock

File diff suppressed because it is too large Load Diff