mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-16 13:01:38 +08:00
Compare commits
27 Commits
v10.3.0-be
...
v10.7.1
Author | SHA1 | Date | |
---|---|---|---|
![]() |
a6d4befca2 | ||
![]() |
4fb0c691e6 | ||
![]() |
b62e6d64cf | ||
![]() |
9af0538a2a | ||
![]() |
e63fa0fdb6 | ||
![]() |
6244bb9af2 | ||
![]() |
9fd6293037 | ||
![]() |
e9e67b011c | ||
![]() |
5996a7aa75 | ||
![]() |
ad9b0778ba | ||
![]() |
3e60cfd80f | ||
![]() |
782b0e5227 | ||
![]() |
d1ecfb3f93 | ||
![]() |
571c2819b9 | ||
![]() |
1f75688b92 | ||
![]() |
de332c1796 | ||
![]() |
80e0451983 | ||
![]() |
b512ae18b7 | ||
![]() |
fe75a2ca9e | ||
![]() |
d84ad103fb | ||
![]() |
208034fa7d | ||
![]() |
c6430a9ed4 | ||
![]() |
f2aec36705 | ||
![]() |
71e5b947d3 | ||
![]() |
5dc8d8defc | ||
![]() |
30687dddf2 | ||
![]() |
57ddcc7758 |
@@ -47,4 +47,6 @@ Example
|
||||
yarn.lock
|
||||
|
||||
domains.json
|
||||
endpoints.json
|
||||
endpoints.json
|
||||
|
||||
tea.yaml
|
@@ -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.2.6",
|
||||
"react-native-update": "^10.6.0-beta.0",
|
||||
"react-native-vector-icons": "^10.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
@@ -66,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: () => {
|
||||
|
@@ -47,7 +47,7 @@ function App() {
|
||||
onValueChange={v => {
|
||||
setUseDefaultAlert(v);
|
||||
client?.setOptions({
|
||||
useAlert: v,
|
||||
updateStrategy: v ? null : 'alwaysAlert',
|
||||
});
|
||||
setShowUpdateSnackbar(!v);
|
||||
}}
|
||||
|
@@ -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.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==
|
||||
react-native-update@^10.6.0-beta.0:
|
||||
version "10.6.0-beta.0"
|
||||
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.6.0-beta.0.tgz#5414989a44f7bc94c97a8c29661c3fc4f43521d8"
|
||||
integrity sha512-p/nTO/0qZhgxcmUXoiBkRvBa1yo3MocbJL4dMHboqOtK3TtUYhilP9O6fZQ9FBev4BjTyHBeXDjwT6eutw9gXg==
|
||||
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() {
|
||||
|
@@ -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)
|
||||
{
|
||||
|
14
package.json
14
package.json
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "react-native-update",
|
||||
"version": "10.3.0-beta.0",
|
||||
"version": "10.7.1",
|
||||
"description": "react-native hot update",
|
||||
"main": "src/index.ts",
|
||||
"main": "src/index",
|
||||
"scripts": {
|
||||
"prepack": "yarn submodule && yarn lint",
|
||||
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
|
||||
@@ -48,13 +48,9 @@
|
||||
"nanoid": "^3.3.3"
|
||||
},
|
||||
"codegenConfig": {
|
||||
"libraries": [
|
||||
{
|
||||
"name": "RCTPushySpec",
|
||||
"type": "modules",
|
||||
"jsSrcsDir": "src"
|
||||
}
|
||||
]
|
||||
"name": "RCTPushySpec",
|
||||
"type": "modules",
|
||||
"jsSrcsDir": "src"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.24.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 { PermissionsAndroid } from './permissions';
|
||||
import {
|
||||
PushyModule,
|
||||
buildTime,
|
||||
@@ -21,20 +18,25 @@ const defaultServer = {
|
||||
main: 'https://update.react-native.cn/api',
|
||||
backups: ['https://update.reactnative.cn/api'],
|
||||
queryUrl:
|
||||
'https://raw.githubusercontent.com/reactnativecn/react-native-pushy/master/endpoints.json',
|
||||
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json',
|
||||
};
|
||||
|
||||
const empty = {};
|
||||
const noop = () => {};
|
||||
|
||||
if (Platform.OS === 'web') {
|
||||
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
|
||||
}
|
||||
|
||||
export class Pushy {
|
||||
options: PushyOptions = {
|
||||
appKey: '',
|
||||
server: defaultServer,
|
||||
autoMarkSuccess: true,
|
||||
useAlert: true,
|
||||
strategy: 'both',
|
||||
updateStrategy: 'alwaysAlert',
|
||||
checkStrategy: 'both',
|
||||
logger: noop,
|
||||
debug: false,
|
||||
};
|
||||
|
||||
lastChecking?: number;
|
||||
@@ -48,8 +50,10 @@ export class Pushy {
|
||||
version = cInfo.pushy;
|
||||
|
||||
constructor(options: PushyOptions) {
|
||||
if (!options.appKey) {
|
||||
throw new Error('appKey is required');
|
||||
if (Platform.OS === 'ios' || Platform.OS === 'android') {
|
||||
if (!options.appKey) {
|
||||
throw new Error('appKey is required');
|
||||
}
|
||||
}
|
||||
this.setOptions(options);
|
||||
}
|
||||
@@ -112,8 +116,7 @@ export class Pushy {
|
||||
return true;
|
||||
};
|
||||
markSuccess = () => {
|
||||
assertRelease();
|
||||
if (this.marked) {
|
||||
if (this.marked || __DEV__) {
|
||||
return;
|
||||
}
|
||||
this.marked = true;
|
||||
@@ -121,7 +124,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;
|
||||
@@ -130,14 +138,28 @@ 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.lastRespJson &&
|
||||
@@ -148,18 +170,22 @@ export class Pushy {
|
||||
}
|
||||
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 {
|
||||
@@ -225,7 +251,6 @@ export class Pushy {
|
||||
info: CheckResult,
|
||||
onDownloadProgress?: (data: ProgressData) => void,
|
||||
) => {
|
||||
assertRelease();
|
||||
const {
|
||||
hash,
|
||||
diffUrl: _diffUrl,
|
||||
@@ -275,7 +300,11 @@ export class Pushy {
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
if (__DEV__) {
|
||||
succeeded = true;
|
||||
} else {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
|
||||
@@ -288,7 +317,11 @@ export class Pushy {
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
if (__DEV__) {
|
||||
succeeded = true;
|
||||
} else {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
|
||||
@@ -301,13 +334,20 @@ export class Pushy {
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
log(`full patch error: ${e.message}`);
|
||||
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',
|
@@ -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;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
11
src/core.ts
11
src/core.ts
@@ -1,5 +1,5 @@
|
||||
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
|
||||
import { log } from './utils';
|
||||
import { emptyModule, log } from './utils';
|
||||
const {
|
||||
version: v,
|
||||
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||
@@ -8,9 +8,12 @@ const isTurboModuleEnabled =
|
||||
// @ts-expect-error
|
||||
global.__turboModuleProxy != null;
|
||||
|
||||
export const PushyModule = isTurboModuleEnabled
|
||||
? require('./turboModuleSpec').default
|
||||
: NativeModules.Pushy;
|
||||
export const PushyModule =
|
||||
Platform.OS === 'web'
|
||||
? emptyModule
|
||||
: isTurboModuleEnabled
|
||||
? require('./NativePushy').default
|
||||
: NativeModules.Pushy;
|
||||
|
||||
if (!PushyModule) {
|
||||
throw new Error('react-native-update模块无法加载,请对照安装文档检查配置。');
|
||||
|
1
src/permissions.native.ts
Normal file
1
src/permissions.native.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { PermissionsAndroid } from 'react-native';
|
4
src/permissions.ts
Normal file
4
src/permissions.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { PermissionsAndroidStatic } from 'react-native';
|
||||
import { emptyModule } from './utils';
|
||||
|
||||
export const PermissionsAndroid = emptyModule as PermissionsAndroidStatic;
|
@@ -41,13 +41,25 @@ export const PushyProvider = ({
|
||||
setLastError(undefined);
|
||||
}, []);
|
||||
|
||||
const showAlert = useCallback(
|
||||
const alertUpdate = useCallback(
|
||||
(...args: Parameters<typeof Alert.alert>) => {
|
||||
if (options.useAlert) {
|
||||
if (
|
||||
options.updateStrategy === 'alwaysAlert' ||
|
||||
options.updateStrategy === 'alertUpdateAndIgnoreError'
|
||||
) {
|
||||
Alert.alert(...args);
|
||||
}
|
||||
},
|
||||
[options],
|
||||
[options.updateStrategy],
|
||||
);
|
||||
|
||||
const alertError = useCallback(
|
||||
(...args: Parameters<typeof Alert.alert>) => {
|
||||
if (options.updateStrategy === 'alwaysAlert') {
|
||||
Alert.alert(...args);
|
||||
}
|
||||
},
|
||||
[options.updateStrategy],
|
||||
);
|
||||
|
||||
const switchVersion = useCallback(() => {
|
||||
@@ -73,7 +85,12 @@ export const PushyProvider = ({
|
||||
return;
|
||||
}
|
||||
stateListener.current && stateListener.current.remove();
|
||||
showAlert('提示', '下载完毕,是否立即更新?', [
|
||||
if (options.updateStrategy === 'silentAndNow') {
|
||||
return client.switchVersion(hash);
|
||||
} else if (options.updateStrategy === 'silentAndLater') {
|
||||
return client.switchVersionLater(hash);
|
||||
}
|
||||
alertUpdate('提示', '下载完毕,是否立即更新?', [
|
||||
{
|
||||
text: '下次再说',
|
||||
style: 'cancel',
|
||||
@@ -91,10 +108,10 @@ export const PushyProvider = ({
|
||||
]);
|
||||
} catch (e: any) {
|
||||
setLastError(e);
|
||||
showAlert('更新失败', e.message);
|
||||
alertError('更新失败', e.message);
|
||||
}
|
||||
},
|
||||
[client, showAlert],
|
||||
[alertError, client, options.updateStrategy, alertUpdate],
|
||||
);
|
||||
|
||||
const downloadAndInstallApk = useCallback(
|
||||
@@ -117,29 +134,46 @@ export const PushyProvider = ({
|
||||
info = await client.checkUpdate();
|
||||
} catch (e: any) {
|
||||
setLastError(e);
|
||||
showAlert('更新检查失败', e.message);
|
||||
alertError('更新检查失败', e.message);
|
||||
return;
|
||||
}
|
||||
if (!info) {
|
||||
return;
|
||||
}
|
||||
updateInfoRef.current = info;
|
||||
setUpdateInfo(info);
|
||||
if (info.expired) {
|
||||
const { downloadUrl } = info;
|
||||
showAlert('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||
{
|
||||
text: '更新',
|
||||
onPress: () => {
|
||||
if (downloadUrl) {
|
||||
if (downloadUrl) {
|
||||
if (options.updateStrategy === 'silentAndNow') {
|
||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||
downloadAndInstallApk(downloadUrl);
|
||||
} else {
|
||||
Linking.openURL(downloadUrl);
|
||||
}
|
||||
return;
|
||||
}
|
||||
alertUpdate('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||
{
|
||||
text: '更新',
|
||||
onPress: () => {
|
||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||
downloadAndInstallApk(downloadUrl);
|
||||
} else {
|
||||
Linking.openURL(downloadUrl);
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
]);
|
||||
}
|
||||
} else if (info.update) {
|
||||
showAlert(
|
||||
if (
|
||||
options.updateStrategy === 'silentAndNow' ||
|
||||
options.updateStrategy === 'silentAndLater'
|
||||
) {
|
||||
return downloadUpdate(info);
|
||||
}
|
||||
alertUpdate(
|
||||
'提示',
|
||||
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
|
||||
[
|
||||
@@ -154,20 +188,29 @@ export const PushyProvider = ({
|
||||
],
|
||||
);
|
||||
}
|
||||
}, [client, downloadAndInstallApk, downloadUpdate, showAlert]);
|
||||
}, [
|
||||
alertError,
|
||||
client,
|
||||
downloadAndInstallApk,
|
||||
downloadUpdate,
|
||||
options.updateStrategy,
|
||||
alertUpdate,
|
||||
]);
|
||||
|
||||
const markSuccess = client.markSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (__DEV__) {
|
||||
console.info('检测到在DEV环境,不会进行热更新检查');
|
||||
if (__DEV__ && !options.debug) {
|
||||
console.info(
|
||||
'您当前处于开发环境且未启用debug,不会进行热更检查。如需在开发环境中调试热更,请在client中设置debug为true',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||
if (isFirstTime && autoMarkSuccess) {
|
||||
markSuccess();
|
||||
}
|
||||
if (strategy === 'both' || strategy === 'onAppResume') {
|
||||
if (checkStrategy === 'both' || checkStrategy === 'onAppResume') {
|
||||
stateListener.current = AppState.addEventListener(
|
||||
'change',
|
||||
nextAppState => {
|
||||
@@ -177,7 +220,7 @@ export const PushyProvider = ({
|
||||
},
|
||||
);
|
||||
}
|
||||
if (strategy === 'both' || strategy === 'onAppStart') {
|
||||
if (checkStrategy === 'both' || checkStrategy === 'onAppStart') {
|
||||
checkUpdate();
|
||||
}
|
||||
let dismissErrorTimer: ReturnType<typeof setTimeout>;
|
||||
|
@@ -1,2 +0,0 @@
|
||||
import { Fragment } from 'react';
|
||||
export const PushyProvider = Fragment;
|
10
src/type.ts
10
src/type.ts
@@ -69,8 +69,14 @@ export interface PushyOptions {
|
||||
appKey: string;
|
||||
server?: PushyServerConfig;
|
||||
logger?: UpdateEventsLogger;
|
||||
useAlert?: boolean;
|
||||
strategy?: 'onAppStart' | 'onAppResume' | 'both';
|
||||
updateStrategy?:
|
||||
| 'alwaysAlert'
|
||||
| 'alertUpdateAndIgnoreError'
|
||||
| 'silentAndNow'
|
||||
| 'silentAndLater'
|
||||
| null;
|
||||
checkStrategy?: 'onAppStart' | 'onAppResume' | 'both' | null;
|
||||
autoMarkSuccess?: boolean;
|
||||
dismissErrorAfter?: number;
|
||||
debug?: boolean;
|
||||
}
|
||||
|
37
src/utils.ts
37
src/utils.ts
@@ -1,20 +1,33 @@
|
||||
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 noop = () => {};
|
||||
class EmptyModule {
|
||||
constructor() {
|
||||
return new Proxy(this, {
|
||||
get() {
|
||||
return noop;
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
export const emptyModule = new EmptyModule();
|
||||
|
||||
const ping = async (url: string) =>
|
||||
Promise.race([
|
||||
fetch(url, {
|
||||
method: 'HEAD',
|
||||
}).then(({ status }) => status === 200),
|
||||
new Promise<false>(r => setTimeout(() => r(false), 2000)),
|
||||
]);
|
||||
const ping =
|
||||
Platform.OS === 'web'
|
||||
? Promise.resolve
|
||||
: async (url: string) =>
|
||||
Promise.race([
|
||||
fetch(url, {
|
||||
method: 'HEAD',
|
||||
})
|
||||
.then(({ status }) => (status === 200 ? url : null))
|
||||
.catch(() => null),
|
||||
new Promise(r => setTimeout(() => r(null), 2000)),
|
||||
]);
|
||||
|
||||
const canUseGoogle = ping('https://www.google.com');
|
||||
|
||||
@@ -22,7 +35,5 @@ 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,
|
||||
);
|
||||
return Promise.race(urls.map(ping)).catch(() => null);
|
||||
};
|
||||
|
Reference in New Issue
Block a user