mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-16 13:01:38 +08:00
Compare commits
33 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
b66b4dea06 | ||
![]() |
ad9b0778ba | ||
![]() |
3e60cfd80f | ||
![]() |
782b0e5227 | ||
![]() |
d1ecfb3f93 | ||
![]() |
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 |
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;
|
||||
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',
|
||||
|
@@ -47,4 +47,6 @@ Example
|
||||
yarn.lock
|
||||
|
||||
domains.json
|
||||
endpoints.json
|
||||
endpoints.json
|
||||
|
||||
tea.yaml
|
@@ -1,4 +1,6 @@
|
||||
module.exports = {
|
||||
trailingComma: 'all',
|
||||
arrowParens: 'avoid',
|
||||
bracketSameLine: true,
|
||||
singleQuote: true,
|
||||
trailingComma: 'all',
|
||||
};
|
||||
|
@@ -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();
|
||||
|
@@ -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.2",
|
||||
"react-native-update": "^10.2.6",
|
||||
"react-native-vector-icons": "^10.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
@@ -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>
|
||||
);
|
||||
|
@@ -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.2:
|
||||
version "10.0.2"
|
||||
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.2.tgz#2bb01ab6e41e72bbbb535cebd34083b1fed69eb0"
|
||||
integrity sha512-XkEPmTC3X6FV1eXq6uDyjfhXpAaug0HI48Mm+PkbMlXcgFjTrOmtuq7yuvemS2nPG2pwnrYQuGs0A6tE2aoRBA==
|
||||
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"
|
||||
|
||||
|
@@ -69,13 +69,6 @@ public class UpdateContext {
|
||||
return context.getString(R.string.pushy_build_time);
|
||||
}
|
||||
|
||||
public Map getBlockUpdate() {
|
||||
return new HashMap<String, Object>() {{
|
||||
put("until", sp.getInt("blockUntil", 0));
|
||||
put("reason", sp.getString("blockReason", null));
|
||||
}};
|
||||
}
|
||||
|
||||
public boolean getIsUsingBundleUrl() {
|
||||
return isUsingBundleUrl;
|
||||
}
|
||||
@@ -166,13 +159,6 @@ public class UpdateContext {
|
||||
return sp.getString(key, null);
|
||||
}
|
||||
|
||||
public void setBlockUpdate(int until, String reason) {
|
||||
SharedPreferences.Editor editor = sp.edit();
|
||||
editor.putInt("blockUntil", until);
|
||||
editor.putString("blockReason", reason);
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
public String getCurrentVersion() {
|
||||
return sp.getString("currentVersion", null);
|
||||
}
|
||||
|
@@ -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() {
|
||||
|
@@ -14,7 +14,7 @@ import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class UpdateModule extends NativeUpdateSpec {
|
||||
public class UpdateModule extends NativePushySpec {
|
||||
UpdateContext updateContext;
|
||||
public static ReactApplicationContext mContext;
|
||||
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
|
||||
@@ -45,7 +45,6 @@ public class UpdateModule extends NativeUpdateSpec {
|
||||
if (rolledBackVersion != null) {
|
||||
updateContext.clearRollbackMark();
|
||||
}
|
||||
constants.put("blockUpdate", updateContext.getBlockUpdate());
|
||||
constants.put("uuid", updateContext.getKv("uuid"));
|
||||
return constants;
|
||||
}
|
||||
@@ -108,11 +107,6 @@ public class UpdateModule extends NativeUpdateSpec {
|
||||
UpdateModuleImpl.markSuccess(updateContext,promise);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlockUpdate(ReadableMap options,Promise promise) {
|
||||
UpdateModuleImpl.setBlockUpdate(updateContext,options,promise);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUuid(final String uuid, Promise promise) {
|
||||
UpdateModuleImpl.setUuid(updateContext,uuid,promise);
|
||||
|
@@ -59,7 +59,6 @@ public class UpdateModule extends ReactContextBaseJavaModule {
|
||||
if (rolledBackVersion != null) {
|
||||
updateContext.clearRollbackMark();
|
||||
}
|
||||
constants.put("blockUpdate", updateContext.getBlockUpdate());
|
||||
constants.put("uuid", updateContext.getKv("uuid"));
|
||||
return constants;
|
||||
}
|
||||
@@ -239,18 +238,6 @@ public class UpdateModule extends ReactContextBaseJavaModule {
|
||||
});
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void setBlockUpdate(ReadableMap options) {
|
||||
final int until = options.getInt("until");
|
||||
final String reason = options.getString("reason");
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateContext.setBlockUpdate(until, reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void setUuid(final String uuid) {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
|
3
babel.config.js
Normal file
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 paramIsFirstTime = @"isFirstTime";
|
||||
static NSString *const paramIsFirstLoadOk = @"isFirstLoadOK";
|
||||
static NSString *const keyBlockUpdate = @"REACTNATIVECN_PUSHY_BLOCKUPDATE";
|
||||
static NSString *const keyUuid = @"REACTNATIVECN_PUSHY_UUID";
|
||||
static NSString *const keyHashInfo = @"REACTNATIVECN_PUSHY_HASH_";
|
||||
static NSString *const keyFirstLoadMarked = @"REACTNATIVECN_PUSHY_FIRSTLOADMARKED_KEY";
|
||||
@@ -157,7 +156,6 @@ RCT_EXPORT_MODULE(RCTPushy);
|
||||
ret[@"buildTime"] = [RCTPushy buildTime];
|
||||
ret[@"rolledBackVersion"] = [defaults objectForKey:keyRolledBackMarked];
|
||||
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
|
||||
ret[@"blockUpdate"] = [defaults objectForKey:keyBlockUpdate];
|
||||
ret[@"uuid"] = [defaults objectForKey:keyUuid];
|
||||
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
|
||||
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
|
||||
@@ -192,24 +190,6 @@ RCT_EXPORT_MODULE(RCTPushy);
|
||||
return self;
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(setBlockUpdate:(NSDictionary *)options
|
||||
resolver:(RCTPromiseResolveBlock)resolve
|
||||
rejecter:(RCTPromiseRejectBlock)reject)
|
||||
{
|
||||
// NSMutableDictionary *blockUpdateInfo = [NSMutableDictionary new];
|
||||
// blockUpdateInfo[@"reason"] = options[@"reason"];
|
||||
// blockUpdateInfo[@"until"] = options[@"until"];
|
||||
@try {
|
||||
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
||||
[defaults setObject:options forKey:keyBlockUpdate];
|
||||
[defaults synchronize];
|
||||
resolve(@true);
|
||||
}
|
||||
@catch (NSException *exception) {
|
||||
reject(@"执行报错", nil, nil);
|
||||
}
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(setUuid:(NSString *)uuid resolver:(RCTPromiseResolveBlock)resolve
|
||||
rejecter:(RCTPromiseRejectBlock)reject)
|
||||
{
|
||||
|
25
package.json
25
package.json
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"name": "react-native-update",
|
||||
"version": "10.2.1",
|
||||
"version": "10.5.2",
|
||||
"description": "react-native hot update",
|
||||
"main": "src/index.ts",
|
||||
"main": "src/index",
|
||||
"scripts": {
|
||||
"prepublish": "yarn submodule",
|
||||
"prepack": "yarn submodule && yarn lint",
|
||||
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
|
||||
"submodule": "git submodule update --init --recursive",
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"build-lib": "yarn submodule && $ANDROID_HOME/ndk/20.1.5948944/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib",
|
||||
@@ -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",
|
||||
|
@@ -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: () => {
|
@@ -1,10 +1,7 @@
|
||||
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
|
||||
import { assertRelease, log, testUrls } from './utils';
|
||||
import {
|
||||
EmitterSubscription,
|
||||
PermissionsAndroid,
|
||||
Platform,
|
||||
} from 'react-native';
|
||||
import { log, testUrls } from './utils';
|
||||
import { EmitterSubscription, Platform } from 'react-native';
|
||||
import type { PermissionsAndroidStatic } from 'react-native';
|
||||
import {
|
||||
PushyModule,
|
||||
buildTime,
|
||||
@@ -27,6 +24,10 @@ const defaultServer = {
|
||||
const empty = {};
|
||||
const noop = () => {};
|
||||
|
||||
if (Platform.OS === 'web') {
|
||||
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
|
||||
}
|
||||
|
||||
export class Pushy {
|
||||
options: PushyOptions = {
|
||||
appKey: '',
|
||||
@@ -35,13 +36,14 @@ export class Pushy {
|
||||
useAlert: true,
|
||||
strategy: 'both',
|
||||
logger: noop,
|
||||
debug: false,
|
||||
};
|
||||
|
||||
lastChecking: number;
|
||||
lastResult: CheckResult;
|
||||
lastChecking?: number;
|
||||
lastRespJson?: Promise<any>;
|
||||
|
||||
progressHandlers: Record<string, EmitterSubscription> = {};
|
||||
downloadedHash: string;
|
||||
downloadedHash?: string;
|
||||
|
||||
marked = false;
|
||||
applyingUpdate = false;
|
||||
@@ -57,6 +59,7 @@ 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) {
|
||||
@@ -111,8 +114,7 @@ export class Pushy {
|
||||
return true;
|
||||
};
|
||||
markSuccess = () => {
|
||||
assertRelease();
|
||||
if (this.marked) {
|
||||
if (this.marked || __DEV__) {
|
||||
return;
|
||||
}
|
||||
this.marked = true;
|
||||
@@ -120,7 +122,12 @@ export class Pushy {
|
||||
this.report({ type: 'markSuccess' });
|
||||
};
|
||||
switchVersion = (hash: string) => {
|
||||
assertRelease();
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
'您调用了switchVersion方法,但是当前是开发环境,不会进行任何操作。',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.assertHash(hash) && !this.applyingUpdate) {
|
||||
log('switchVersion: ' + hash);
|
||||
this.applyingUpdate = true;
|
||||
@@ -129,41 +136,59 @@ export class Pushy {
|
||||
};
|
||||
|
||||
switchVersionLater = (hash: string) => {
|
||||
assertRelease();
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
'您调用了switchVersionLater方法,但是当前是开发环境,不会进行任何操作。',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.assertHash(hash)) {
|
||||
log('switchVersionLater: ' + hash);
|
||||
PushyModule.setNeedUpdate({ hash });
|
||||
}
|
||||
};
|
||||
checkUpdate = async () => {
|
||||
assertRelease();
|
||||
if (__DEV__ && !this.options.debug) {
|
||||
console.info(
|
||||
'您当前处于开发环境且未启用 debug,不会进行热更检查。如需在开发环境中调试热更,请在 client 中设置 debug 为 true',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (Platform.OS === 'web') {
|
||||
console.warn('web 端不支持热更新检查');
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (
|
||||
this.lastResult &&
|
||||
this.lastRespJson &&
|
||||
this.lastChecking &&
|
||||
now - this.lastChecking < 1000 * 5
|
||||
) {
|
||||
return this.lastResult;
|
||||
return await this.lastRespJson;
|
||||
}
|
||||
this.lastChecking = now;
|
||||
this.report({ type: 'checking' });
|
||||
const fetchBody = {
|
||||
packageVersion,
|
||||
hash: currentVersion,
|
||||
buildTime,
|
||||
cInfo,
|
||||
};
|
||||
if (__DEV__) {
|
||||
delete fetchBody.buildTime;
|
||||
}
|
||||
const fetchPayload = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
packageVersion,
|
||||
hash: currentVersion,
|
||||
buildTime,
|
||||
cInfo,
|
||||
}),
|
||||
body: JSON.stringify(fetchBody),
|
||||
};
|
||||
let resp;
|
||||
try {
|
||||
resp = await fetch(this.getCheckUrl(), fetchPayload);
|
||||
} catch (e) {
|
||||
} catch (e: any) {
|
||||
this.report({
|
||||
type: 'errorChecking',
|
||||
message: 'Can not connect to update server. Trying backup endpoints.',
|
||||
@@ -172,7 +197,7 @@ export class Pushy {
|
||||
if (backupEndpoints) {
|
||||
try {
|
||||
resp = await Promise.race(
|
||||
backupEndpoints.map((endpoint) =>
|
||||
backupEndpoints.map(endpoint =>
|
||||
fetch(this.getCheckUrl(endpoint), fetchPayload),
|
||||
),
|
||||
);
|
||||
@@ -184,11 +209,11 @@ export class Pushy {
|
||||
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) {
|
||||
this.report({
|
||||
@@ -214,7 +239,7 @@ export class Pushy {
|
||||
new Set([...(server.backups || []), ...remoteEndpoints]),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
} catch (e: any) {
|
||||
log('failed to fetch endpoints from: ', server.queryUrl);
|
||||
}
|
||||
}
|
||||
@@ -224,7 +249,6 @@ export class Pushy {
|
||||
info: CheckResult,
|
||||
onDownloadProgress?: (data: ProgressData) => void,
|
||||
) => {
|
||||
assertRelease();
|
||||
const {
|
||||
hash,
|
||||
diffUrl: _diffUrl,
|
||||
@@ -254,7 +278,7 @@ export class Pushy {
|
||||
if (onDownloadProgress) {
|
||||
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
|
||||
'RCTPushyDownloadProgress',
|
||||
(progressData) => {
|
||||
progressData => {
|
||||
if (progressData.hash === hash) {
|
||||
onDownloadProgress(progressData);
|
||||
}
|
||||
@@ -273,8 +297,12 @@ export class Pushy {
|
||||
originHash: currentVersion,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e) {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
} catch (e: any) {
|
||||
if (__DEV__) {
|
||||
succeeded = true;
|
||||
} else {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
|
||||
@@ -286,8 +314,12 @@ export class Pushy {
|
||||
hash,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e) {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
} catch (e: any) {
|
||||
if (__DEV__) {
|
||||
succeeded = true;
|
||||
} else {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
|
||||
@@ -299,14 +331,21 @@ export class Pushy {
|
||||
hash,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e) {
|
||||
log(`full patch error: ${e.message}`);
|
||||
} catch (e: any) {
|
||||
if (__DEV__) {
|
||||
succeeded = true;
|
||||
} else {
|
||||
log(`full patch error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.progressHandlers[hash]) {
|
||||
this.progressHandlers[hash].remove();
|
||||
delete this.progressHandlers[hash];
|
||||
}
|
||||
if (__DEV__) {
|
||||
return hash;
|
||||
}
|
||||
if (!succeeded) {
|
||||
return this.report({
|
||||
type: 'errorUpdate',
|
||||
@@ -332,13 +371,15 @@ export class Pushy {
|
||||
this.report({ type: 'downloadingApk' });
|
||||
if (Platform.Version <= 23) {
|
||||
try {
|
||||
const PermissionsAndroid =
|
||||
require('react-native/Libraries/PermissionsAndroid/PermissionsAndroid') as PermissionsAndroidStatic;
|
||||
const granted = await PermissionsAndroid.request(
|
||||
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
|
||||
);
|
||||
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
|
||||
return this.report({ type: 'rejectStoragePermission' });
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (e: any) {
|
||||
return this.report({ type: 'errorStoragePermission' });
|
||||
}
|
||||
}
|
@@ -1,13 +0,0 @@
|
||||
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;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
24
src/core.ts
24
src/core.ts
@@ -4,11 +4,27 @@ 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
|
||||
: NativeModules.Pushy;
|
||||
const noop = () => {};
|
||||
class EmptyModule {
|
||||
constructor() {
|
||||
return new Proxy(this, {
|
||||
get() {
|
||||
return noop;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const PushyModule =
|
||||
Platform.OS === 'web'
|
||||
? new EmptyModule()
|
||||
: isTurboModuleEnabled
|
||||
? require('./NativePushy').default
|
||||
: NativeModules.Pushy;
|
||||
|
||||
if (!PushyModule) {
|
||||
throw new Error('react-native-update模块无法加载,请对照安装文档检查配置。');
|
||||
|
@@ -32,8 +32,10 @@ export const PushyProvider = ({
|
||||
const { options } = client;
|
||||
const stateListener = useRef<NativeEventSubscription>();
|
||||
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
|
||||
const updateInfoRef = useRef(updateInfo);
|
||||
const [progress, setProgress] = useState<ProgressData>();
|
||||
const [lastError, setLastError] = useState<Error>();
|
||||
const lastChecking = useRef(0);
|
||||
|
||||
const dismissError = useCallback(() => {
|
||||
setLastError(undefined);
|
||||
@@ -60,37 +62,40 @@ export const PushyProvider = ({
|
||||
}
|
||||
}, [client, updateInfo]);
|
||||
|
||||
const downloadUpdate = useCallback(async () => {
|
||||
if (!updateInfo || !updateInfo.update) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const hash = await client.downloadUpdate(updateInfo, setProgress);
|
||||
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) => {
|
||||
@@ -102,31 +107,37 @@ export const PushyProvider = ({
|
||||
);
|
||||
|
||||
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 (info.expired) {
|
||||
const { downloadUrl } = info;
|
||||
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||
{
|
||||
text: '更新',
|
||||
onPress: () => {
|
||||
if (downloadUrl) {
|
||||
if (downloadUrl) {
|
||||
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||
{
|
||||
text: '更新',
|
||||
onPress: () => {
|
||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||
downloadAndInstallApk(downloadUrl);
|
||||
} else {
|
||||
Linking.openURL(downloadUrl);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
]);
|
||||
}
|
||||
} else if (info.update) {
|
||||
showAlert(
|
||||
'提示',
|
||||
@@ -148,6 +159,12 @@ export const PushyProvider = ({
|
||||
const markSuccess = client.markSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (__DEV__ && !options.debug) {
|
||||
console.info(
|
||||
'您当前处于开发环境且未启用debug,不会进行热更检查。如需在开发环境中调试热更,请在client中设置debug为true',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||
if (isFirstTime && autoMarkSuccess) {
|
||||
markSuccess();
|
||||
@@ -155,7 +172,7 @@ export const PushyProvider = ({
|
||||
if (strategy === 'both' || strategy === 'onAppResume') {
|
||||
stateListener.current = AppState.addEventListener(
|
||||
'change',
|
||||
(nextAppState) => {
|
||||
nextAppState => {
|
||||
if (nextAppState === 'active') {
|
||||
checkUpdate();
|
||||
}
|
||||
@@ -194,8 +211,7 @@ export const PushyProvider = ({
|
||||
progress,
|
||||
downloadAndInstallApk,
|
||||
getCurrentVersionInfo,
|
||||
}}
|
||||
>
|
||||
}}>
|
||||
{children}
|
||||
</PushyContext.Provider>
|
||||
);
|
||||
|
@@ -1,2 +0,0 @@
|
||||
import { Fragment } from 'react';
|
||||
export const PushyProvider = Fragment;
|
@@ -70,7 +70,8 @@ export interface PushyOptions {
|
||||
server?: PushyServerConfig;
|
||||
logger?: UpdateEventsLogger;
|
||||
useAlert?: boolean;
|
||||
strategy?: 'onAppStart' | 'onAppResume' | 'both';
|
||||
strategy?: 'onAppStart' | 'onAppResume' | 'both' | null;
|
||||
autoMarkSuccess?: boolean;
|
||||
dismissErrorAfter?: number;
|
||||
debug?: boolean;
|
||||
}
|
||||
|
24
src/utils.ts
24
src/utils.ts
@@ -1,18 +1,18 @@
|
||||
import { Platform } from 'react-native';
|
||||
export function log(...args: any[]) {
|
||||
console.log('pushy: ', ...args);
|
||||
}
|
||||
|
||||
export function assertRelease() {
|
||||
if (__DEV__) {
|
||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
||||
}
|
||||
}
|
||||
|
||||
const ping = async (url: string) =>
|
||||
fetch(url, {
|
||||
method: 'HEAD',
|
||||
redirect: 'follow',
|
||||
}).then(({ status }) => status === 200);
|
||||
const ping =
|
||||
Platform.OS === 'web'
|
||||
? () => Promise.resolve(true)
|
||||
: 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');
|
||||
|
||||
@@ -20,7 +20,7 @@ export const testUrls = async (urls?: string[]) => {
|
||||
if (!urls?.length || (await canUseGoogle)) {
|
||||
return null;
|
||||
}
|
||||
return Promise.race(urls.map((url) => ping(url).then(() => url))).catch(
|
||||
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