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

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
4231d377e6 v10.0.2 2024-02-19 11:41:47 +08:00
28 changed files with 658 additions and 931 deletions

4
.eslintrc Normal file
View File

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

View File

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

View File

@@ -41,17 +41,14 @@ 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( throw new functions.https.HttpsError('invalid-argument', 'Invalid test requested.');
'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: any) { } catch (e) {
console.error(e); console.error(e);
throw new functions.https.HttpsError( throw new functions.https.HttpsError(
'invalid-argument', 'invalid-argument',

View File

@@ -48,5 +48,3 @@ yarn.lock
domains.json domains.json
endpoints.json endpoints.json
tea.yaml

View File

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

View File

@@ -29,6 +29,13 @@ describe('测试Native模块的方法', () => {
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();

View File

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

View File

@@ -19,25 +19,23 @@ 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;
}
return ( const CustomDialog = ({title, visible, onConfirm}) => {
<View style={styles.overlay}> if (!visible) {
<View style={styles.dialog}> return null;
<Text style={styles.title}>{title}</Text> }
<TouchableOpacity
testID="done" return (
style={styles.button} <View style={styles.overlay}>
onLongPress={onConfirm}> <View style={styles.dialog}>
<Text style={styles.buttonText}>确认</Text> <Text style={styles.title}>{title}</Text>
</TouchableOpacity> <TouchableOpacity testID='done' style={styles.button} onLongPress={onConfirm}>
<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);
@@ -66,6 +64,13 @@ 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: () => {
@@ -127,8 +132,9 @@ 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>,
); );
} }
@@ -158,14 +164,8 @@ export default function TestConsole({visible}) {
/> />
{running && <ActivityIndicator />} {running && <ActivityIndicator />}
<TouchableOpacity <TouchableOpacity
style={{ style={{backgroundColor:'rgb(0,140,237)', justifyContent: 'center',
backgroundColor: 'rgb(0,140,237)', alignItems: 'center',paddingTop:10,paddingBottom:10,marginBottom:5}}
justifyContent: 'center',
alignItems: 'center',
paddingTop: 10,
paddingBottom: 10,
marginBottom: 5,
}}
testID="submit" testID="submit"
onLongPress={async () => { onLongPress={async () => {
setRunning(true); setRunning(true);
@@ -195,18 +195,17 @@ export default function TestConsole({visible}) {
setAlertMsg(e.message); setAlertMsg(e.message);
} }
setRunning(false); setRunning(false);
}}>
<Text style={{color: 'white'}}>执行</Text>
</TouchableOpacity>
<Button title="重置" onPress={() => setText('')} />
{renderTestView()}
<CustomDialog
title={alertMsg}
visible={alertVisible}
onConfirm={() => {
setAlertVisible(false);
}} }}
/> >
<Text style={{color:'white'}}>执行</Text>
</TouchableOpacity>
<Button title="重置" onPress={() => setText('')} />
{renderTestView()}
<CustomDialog
title={alertMsg}
visible={alertVisible}
onConfirm={()=>{setAlertVisible(false)}}
/>
</SafeAreaView> </SafeAreaView>
</Modal> </Modal>
); );

View File

@@ -6231,10 +6231,10 @@ react-native-safe-area-context@^4.8.2:
resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65" resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65"
integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ== integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ==
react-native-update@^10.2.6: react-native-update@^10.0.0-beta.3:
version "10.2.6" version "10.0.0-beta.3"
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.2.6.tgz#976c1d1b48ac3522677b5ecbfe3e64fa04df1839" resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.0-beta.3.tgz#cad099ebb40ff04b31ba2df13930517039e4fae3"
integrity sha512-x72ga106wEWsinHSN/ANk+YygvGq6hyTEVOCibakps7Wb+5JgTiMeE0p2+GOOPhuxMavEHiil5WdhYOipI3/Qg== integrity sha512-Ak1ylgHbOUeaNsq3ItZGRenqqAwYKSTlB6T4sBn4PPNGaMmIMt6uIKKWrQqcNyc9WEy9LlFM6kSqQXBQdaVatw==
dependencies: dependencies:
nanoid "^3.3.3" nanoid "^3.3.3"

View File

@@ -69,6 +69,13 @@ 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;
} }
@@ -159,6 +166,13 @@ 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);
} }

View File

@@ -192,6 +192,23 @@ 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() {

View File

@@ -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 NativePushySpec { public class UpdateModule extends NativeUpdateSpec {
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,6 +45,7 @@ public class UpdateModule extends NativePushySpec {
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;
} }
@@ -107,6 +108,11 @@ public class UpdateModule extends NativePushySpec {
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);

View File

@@ -59,6 +59,7 @@ 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;
} }
@@ -238,6 +239,18 @@ 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() {

View File

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

View File

@@ -16,6 +16,7 @@ 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";
@@ -156,6 +157,7 @@ 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];
@@ -190,6 +192,24 @@ 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)
{ {

View File

@@ -1,11 +1,10 @@
{ {
"name": "react-native-update", "name": "react-native-update",
"version": "10.5.2", "version": "10.0.2",
"description": "react-native hot update", "description": "react-native hot update",
"main": "src/index", "main": "src/index.ts",
"scripts": { "scripts": {
"prepack": "yarn submodule && yarn lint", "prepublish": "yarn submodule",
"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",
@@ -48,25 +47,25 @@
"nanoid": "^3.3.3" "nanoid": "^3.3.3"
}, },
"codegenConfig": { "codegenConfig": {
"name": "RCTPushySpec", "libraries": [
"type": "modules", {
"jsSrcsDir": "src" "name": "RCTPushySpec",
"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.57.0", "eslint": "^8.56.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.7.0", "jest": "^29.2.1",
"pod-install": "^0.1.37", "pod-install": "^0.1.37",
"prettier": "^2", "prettier": "^2",
"react": "18.2.0", "react": "18.2.0",

View File

@@ -1,7 +1,10 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type'; import { CheckResult, PushyOptions, ProgressData } from './type';
import { log, testUrls } from './utils'; import { assertRelease, log } from './utils';
import { EmitterSubscription, Platform } from 'react-native'; import {
import type { PermissionsAndroidStatic } from 'react-native'; EmitterSubscription,
PermissionsAndroid,
Platform,
} from 'react-native';
import { import {
PushyModule, PushyModule,
buildTime, buildTime,
@@ -9,9 +12,9 @@ import {
pushyNativeEventEmitter, pushyNativeEventEmitter,
currentVersion, currentVersion,
packageVersion, packageVersion,
report,
rolledBackVersion, rolledBackVersion,
setLocalHashInfo, setLocalHashInfo,
isRolledBack,
} from './core'; } from './core';
const defaultServer = { const defaultServer = {
@@ -22,12 +25,6 @@ const defaultServer = {
}; };
const empty = {}; const empty = {};
const noop = () => {};
if (Platform.OS === 'web') {
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
}
export class Pushy { export class Pushy {
options: PushyOptions = { options: PushyOptions = {
appKey: '', appKey: '',
@@ -35,15 +32,13 @@ export class Pushy {
autoMarkSuccess: true, autoMarkSuccess: true,
useAlert: true, useAlert: true,
strategy: 'both', strategy: 'both',
logger: noop,
debug: false,
}; };
lastChecking?: number; lastChecking: number;
lastRespJson?: Promise<any>; lastResult: CheckResult;
progressHandlers: Record<string, EmitterSubscription> = {}; progressHandlers: Record<string, EmitterSubscription> = {};
downloadedHash?: string; downloadedHash: string;
marked = false; marked = false;
applyingUpdate = false; applyingUpdate = false;
@@ -59,47 +54,11 @@ 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}`;
}; };
@@ -114,20 +73,16 @@ export class Pushy {
return true; return true;
}; };
markSuccess = () => { markSuccess = () => {
if (this.marked || __DEV__) { assertRelease();
if (this.marked) {
return; return;
} }
this.marked = true; this.marked = true;
PushyModule.markSuccess(); PushyModule.markSuccess();
this.report({ type: 'markSuccess' }); report({ type: 'markSuccess' });
}; };
switchVersion = (hash: string) => { switchVersion = (hash: string) => {
if (__DEV__) { assertRelease();
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;
@@ -136,60 +91,42 @@ export class Pushy {
}; };
switchVersionLater = (hash: string) => { switchVersionLater = (hash: string) => {
if (__DEV__) { assertRelease();
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 () => {
if (__DEV__ && !this.options.debug) { assertRelease();
console.info(
'您当前处于开发环境且未启用 debug不会进行热更检查。如需在开发环境中调试热更请在 client 中设置 debug 为 true',
);
return;
}
if (Platform.OS === 'web') {
console.warn('web 端不支持热更新检查');
return;
}
const now = Date.now(); const now = Date.now();
if ( if (
this.lastRespJson && this.lastResult &&
this.lastChecking && this.lastChecking &&
now - this.lastChecking < 1000 * 5 now - this.lastChecking < 1000 * 5
) { ) {
return await this.lastRespJson; return this.lastResult;
} }
this.lastChecking = now; this.lastChecking = now;
this.report({ type: 'checking' }); 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(fetchBody), body: JSON.stringify({
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: any) { } catch (e) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: 'Can not connect to update server. Trying backup endpoints.', message: 'Can not connect to update server. Trying backup endpoints.',
}); });
@@ -197,7 +134,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),
), ),
); );
@@ -205,18 +142,18 @@ export class Pushy {
} }
} }
if (!resp) { if (!resp) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: 'Can not connect to update server. Please check your network.', message: 'Can not connect to update server. Please check your network.',
}); });
return this.lastRespJson ? await this.lastRespJson : empty; return this.lastResult || empty;
} }
this.lastRespJson = resp.json(); const result: CheckResult = await resp.json();
const result: CheckResult = await this.lastRespJson; this.lastResult = result;
if (resp.status !== 200) { if (resp.status !== 200) {
this.report({ report({
type: 'errorChecking', type: 'errorChecking',
message: result.message, message: result.message,
}); });
@@ -239,7 +176,7 @@ export class Pushy {
new Set([...(server.backups || []), ...remoteEndpoints]), new Set([...(server.backups || []), ...remoteEndpoints]),
); );
} }
} catch (e: any) { } catch (e) {
log('failed to fetch endpoints from: ', server.queryUrl); log('failed to fetch endpoints from: ', server.queryUrl);
} }
} }
@@ -249,18 +186,9 @@ export class Pushy {
info: CheckResult, info: CheckResult,
onDownloadProgress?: (data: ProgressData) => void, onDownloadProgress?: (data: ProgressData) => void,
) => { ) => {
const { assertRelease();
hash, const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
diffUrl: _diffUrl, info;
diffUrls,
pdiffUrl: _pdiffUrl,
pdiffUrls,
updateUrl: _updateUrl,
updateUrls,
name,
description,
metaInfo,
} = info;
if (!info.update || !hash) { if (!info.update || !hash) {
return; return;
} }
@@ -278,7 +206,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);
} }
@@ -286,8 +214,7 @@ export class Pushy {
); );
} }
let succeeded = false; let succeeded = false;
this.report({ type: 'downloading' }); report({ type: 'downloading' });
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
if (diffUrl) { if (diffUrl) {
log('downloading diff'); log('downloading diff');
try { try {
@@ -297,15 +224,10 @@ export class Pushy {
originHash: currentVersion, originHash: currentVersion,
}); });
succeeded = true; succeeded = true;
} catch (e: any) { } catch (e) {
if (__DEV__) { log(`diff error: ${e.message}, try pdiff`);
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 {
@@ -314,15 +236,10 @@ export class Pushy {
hash, hash,
}); });
succeeded = true; succeeded = true;
} catch (e: any) { } catch (e) {
if (__DEV__) { log(`pdiff error: ${e.message}, try full patch`);
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 {
@@ -331,23 +248,16 @@ export class Pushy {
hash, hash,
}); });
succeeded = true; succeeded = true;
} catch (e: any) { } catch (e) {
if (__DEV__) { log(`full patch error: ${e.message}`);
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 this.report({ return report({
type: 'errorUpdate', type: 'errorUpdate',
data: { newVersion: hash }, data: { newVersion: hash },
}); });
@@ -368,19 +278,17 @@ export class Pushy {
if (Platform.OS !== 'android') { if (Platform.OS !== 'android') {
return; return;
} }
this.report({ type: 'downloadingApk' }); report({ type: 'downloadingApk' });
if (Platform.Version <= 23) { if (Platform.Version <= 23) {
try { try {
const PermissionsAndroid =
require('react-native/Libraries/PermissionsAndroid/PermissionsAndroid') as PermissionsAndroidStatic;
const granted = await PermissionsAndroid.request( const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
); );
if (granted !== PermissionsAndroid.RESULTS.GRANTED) { if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return this.report({ type: 'rejectStoragePermission' }); return report({ type: 'rejectStoragePermission' });
} }
} catch (e: any) { } catch (err) {
return this.report({ type: 'errorStoragePermission' }); return report({ type: 'errorStoragePermission' });
} }
} }
const progressKey = 'downloadingApk'; const progressKey = 'downloadingApk';
@@ -399,7 +307,7 @@ export class Pushy {
target: 'update.apk', target: 'update.apk',
hash: progressKey, hash: progressKey,
}).catch(() => { }).catch(() => {
this.report({ type: 'errowDownloadAndInstallApk' }); report({ type: 'errowDownloadAndInstallApk' });
}); });
if (this.progressHandlers[progressKey]) { if (this.progressHandlers[progressKey]) {
this.progressHandlers[progressKey].remove(); this.progressHandlers[progressKey].remove();

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,35 +2,29 @@ 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: asyncNoop, checkUpdate: () => Promise.resolve(empty),
switchVersion: noop, switchVersion: noop,
switchVersionLater: noop, switchVersionLater: noop,
markSuccess: noop, markSuccess: noop,
dismissError: noop, dismissError: noop,
downloadUpdate: asyncNoop, downloadUpdate: noop,
downloadAndInstallApk: asyncNoop, downloadAndInstallApk: noop,
getCurrentVersionInfo: () => Promise.resolve({}),
currentHash: '', currentHash: '',
packageVersion: '', packageVersion: '',
}; };
export const PushyContext = createContext<{ export const PushyContext = createContext<{
checkUpdate: () => Promise<void>; checkUpdate: () => void;
switchVersion: () => void; switchVersion: () => void;
switchVersionLater: () => void; switchVersionLater: () => void;
markSuccess: () => void; markSuccess: () => void;
dismissError: () => void; dismissError: () => void;
downloadUpdate: () => Promise<void>; downloadUpdate: () => void;
downloadAndInstallApk: (url: string) => Promise<void>; downloadAndInstallApk: (url: string) => void;
getCurrentVersionInfo: () => Promise<{
name?: string;
description?: string;
metaInfo?: string;
}>;
currentHash: string; currentHash: string;
packageVersion: string; packageVersion: string;
client?: Pushy; client?: Pushy;

View File

@@ -1,30 +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 = const isTurboModuleEnabled = global.__turboModuleProxy != null;
// @ts-expect-error
global.__turboModuleProxy != null;
const noop = () => {}; export const PushyModule = isTurboModuleEnabled
class EmptyModule { ? require('./turboModuleSpec').default
constructor() { : NativeModules.Pushy;
return new Proxy(this, {
get() {
return noop;
},
});
}
}
export const PushyModule =
Platform.OS === 'web'
? new EmptyModule()
: isTurboModuleEnabled
? require('./NativePushy').default
: NativeModules.Pushy;
if (!PushyModule) { if (!PushyModule) {
throw new Error('react-native-update模块无法加载请对照安装文档检查配置。'); throw new Error('react-native-update模块无法加载请对照安装文档检查配置。');
@@ -73,6 +58,44 @@ if (!uuid) {
PushyModule.setUuid(uuid); PushyModule.setUuid(uuid);
} }
const noop = () => {};
let reporter: UpdateEventsLogger = noop;
export function onPushyEvents(customReporter: UpdateEventsLogger) {
reporter = customReporter;
if (isRolledBack) {
report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
export function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
log(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
}
log('uuid: ' + uuid); log('uuid: ' + uuid);
export const cInfo = { export const cInfo = {

View File

@@ -13,12 +13,7 @@ import {
Linking, Linking,
} from 'react-native'; } from 'react-native';
import { Pushy } from './client'; import { Pushy } from './client';
import { import { currentVersion, isFirstTime, packageVersion } from './core';
currentVersion,
isFirstTime,
packageVersion,
getCurrentVersionInfo,
} from './core';
import { CheckResult, ProgressData } from './type'; import { CheckResult, ProgressData } from './type';
import { PushyContext } from './context'; import { PushyContext } from './context';
@@ -32,10 +27,8 @@ export const PushyProvider = ({
const { options } = client; 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 [progress, setProgress] = useState<ProgressData>();
const [lastError, setLastError] = useState<Error>(); const [lastError, setLastError] = useState<Error>();
const lastChecking = useRef(0);
const dismissError = useCallback(() => { const dismissError = useCallback(() => {
setLastError(undefined); setLastError(undefined);
@@ -62,82 +55,73 @@ export const PushyProvider = ({
} }
}, [client, updateInfo]); }, [client, updateInfo]);
const downloadUpdate = useCallback( const downloadUpdate = useCallback(async () => {
async (info: CheckResult | undefined = updateInfoRef.current) => { if (!updateInfo || !updateInfo.update) {
if (!info || !info.update) { return;
}
try {
const hash = await client.downloadUpdate(updateInfo, setProgress);
if (!hash) {
return; return;
} }
try { stateListener.current && stateListener.current.remove();
const hash = await client.downloadUpdate(info, setProgress); showAlert('提示', '下载完毕,是否立即更新?', [
if (!hash) { {
return; text: '下次再说',
} style: 'cancel',
stateListener.current && stateListener.current.remove(); onPress: () => {
showAlert('提示', '下载完毕,是否立即更新?', [ client.switchVersionLater(hash);
{
text: '下次再说',
style: 'cancel',
onPress: () => {
client.switchVersionLater(hash);
},
}, },
{ },
text: '立即更新', {
style: 'default', text: '立即更新',
onPress: () => { style: 'default',
client.switchVersion(hash); onPress: () => {
}, client.switchVersion(hash);
}, },
]); },
} catch (e: any) { ]);
setLastError(e); } catch (err) {
showAlert('更新失败', e.message); setLastError(err);
} showAlert('更新失败', err.message);
}, }
[client, showAlert], }, [client, showAlert, updateInfo]);
);
const downloadAndInstallApk = useCallback( const downloadAndInstallApk = useCallback(
async (downloadUrl: string) => { (downloadUrl: string) => {
if (Platform.OS === 'android' && downloadUrl) { if (Platform.OS === 'android' && downloadUrl) {
await client.downloadAndInstallApk(downloadUrl, setProgress); client.downloadAndInstallApk(downloadUrl, setProgress);
} }
}, },
[client], [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 (e: any) { } catch (err) {
setLastError(e); setLastError(err);
showAlert('更新检查失败', e.message); showAlert('更新检查失败', err.message);
return; return;
} }
updateInfoRef.current = info;
setUpdateInfo(info); setUpdateInfo(info);
if (info.expired) { if (info.expired) {
const { downloadUrl } = info; const { downloadUrl } = info;
if (downloadUrl) { showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [ {
{ text: '更新',
text: '更新', onPress: () => {
onPress: () => { if (downloadUrl) {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) { if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl); downloadAndInstallApk(downloadUrl);
} else { } else {
Linking.openURL(downloadUrl); Linking.openURL(downloadUrl);
} }
}, }
}, },
]); },
} ]);
} else if (info.update) { } else if (info.update) {
showAlert( showAlert(
'提示', '提示',
@@ -159,12 +143,6 @@ export const PushyProvider = ({
const markSuccess = client.markSuccess; const markSuccess = client.markSuccess;
useEffect(() => { useEffect(() => {
if (__DEV__ && !options.debug) {
console.info(
'您当前处于开发环境且未启用debug不会进行热更检查。如需在开发环境中调试热更请在client中设置debug为true',
);
return;
}
const { strategy, dismissErrorAfter, autoMarkSuccess } = options; const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
if (isFirstTime && autoMarkSuccess) { if (isFirstTime && autoMarkSuccess) {
markSuccess(); markSuccess();
@@ -172,7 +150,7 @@ export const PushyProvider = ({
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();
} }
@@ -210,8 +188,8 @@ export const PushyProvider = ({
currentHash: currentVersion, currentHash: currentVersion,
progress, progress,
downloadAndInstallApk, downloadAndInstallApk,
getCurrentVersionInfo, }}
}}> >
{children} {children}
</PushyContext.Provider> </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,4 +1,5 @@
import { TurboModule, TurboModuleRegistry } from 'react-native'; import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule { export interface Spec extends TurboModule {
getConstants: () => { getConstants: () => {

View File

@@ -8,11 +8,8 @@ export interface CheckResult {
description?: string; description?: string;
metaInfo?: string; metaInfo?: string;
pdiffUrl?: string; pdiffUrl?: string;
pdiffUrls?: string[];
diffUrl?: string; diffUrl?: string;
diffUrls?: string[];
updateUrl?: string; updateUrl?: string;
updateUrls?: string[];
paused?: 'app' | 'package'; paused?: 'app' | 'package';
message?: string; message?: string;
} }
@@ -70,8 +67,7 @@ export interface PushyOptions {
server?: PushyServerConfig; server?: PushyServerConfig;
logger?: UpdateEventsLogger; logger?: UpdateEventsLogger;
useAlert?: boolean; useAlert?: boolean;
strategy?: 'onAppStart' | 'onAppResume' | 'both' | null; strategy?: 'onAppStart' | 'onAppResume' | 'both';
autoMarkSuccess?: boolean; autoMarkSuccess?: boolean;
dismissErrorAfter?: number; dismissErrorAfter?: number;
debug?: boolean;
} }

View File

@@ -1,26 +1,9 @@
import { Platform } from 'react-native';
export function log(...args: any[]) { export function log(...args: any[]) {
console.log('pushy: ', ...args); console.log('pushy: ', ...args);
} }
const ping = export function assertRelease() {
Platform.OS === 'web' if (__DEV__) {
? () => Promise.resolve(true) throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
: 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,
);
};

View File

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

View File

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

924
yarn.lock

File diff suppressed because it is too large Load Diff