mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-17 20:26:09 +08:00
Compare commits
1 Commits
v10.3.0
...
v10.0.0-be
Author | SHA1 | Date | |
---|---|---|---|
![]() |
f595b2d957 |
@@ -1,4 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: '@react-native',
|
||||
};
|
@@ -41,17 +41,14 @@ 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: any) {
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
throw new functions.https.HttpsError(
|
||||
'invalid-argument',
|
||||
|
@@ -48,5 +48,3 @@ yarn.lock
|
||||
|
||||
domains.json
|
||||
endpoints.json
|
||||
|
||||
tea.yaml
|
@@ -1,6 +1,4 @@
|
||||
module.exports = {
|
||||
arrowParens: 'avoid',
|
||||
bracketSameLine: true,
|
||||
singleQuote: true,
|
||||
trailingComma: 'all',
|
||||
singleQuote: true,
|
||||
};
|
||||
|
@@ -29,6 +29,13 @@ describe('测试Native模块的方法', () => {
|
||||
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.0.0-beta.1",
|
||||
"react-native-vector-icons": "^10.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
@@ -19,25 +19,23 @@ 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;
|
||||
}
|
||||
|
||||
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>
|
||||
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>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
);
|
||||
};
|
||||
export default function TestConsole({visible}) {
|
||||
const [text, setText] = useState('');
|
||||
const [running, setRunning] = useState(false);
|
||||
@@ -66,6 +64,13 @@ 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: () => {
|
||||
@@ -127,8 +132,9 @@ export default function TestConsole({visible}) {
|
||||
testID={NativeTestMethod[i].name}
|
||||
onLongPress={() => {
|
||||
NativeTestMethod[i].invoke();
|
||||
}}>
|
||||
<Text>{NativeTestMethod[i].name}</Text>
|
||||
}}
|
||||
>
|
||||
<Text>{NativeTestMethod[i].name}</Text>
|
||||
</TouchableOpacity>,
|
||||
);
|
||||
}
|
||||
@@ -158,14 +164,8 @@ 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,18 +195,17 @@ export default function TestConsole({visible}) {
|
||||
setAlertMsg(e.message);
|
||||
}
|
||||
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>
|
||||
</Modal>
|
||||
);
|
||||
|
@@ -33,8 +33,7 @@ function App() {
|
||||
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
|
||||
const [showUpdateSnackbar, setShowUpdateSnackbar] = useState(false);
|
||||
const snackbarVisible =
|
||||
!useDefaultAlert && showUpdateSnackbar && updateInfo?.update;
|
||||
|
||||
showUpdateSnackbar && updateInfo?.update && !useDefaultAlert;
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.welcome}>欢迎使用Pushy热更新服务</Text>
|
||||
@@ -49,7 +48,6 @@ function App() {
|
||||
client?.setOptions({
|
||||
useAlert: v,
|
||||
});
|
||||
setShowUpdateSnackbar(!v);
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
@@ -68,11 +66,7 @@ function App() {
|
||||
<Text>
|
||||
下载进度:{received} / {total}
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
onPress={() => {
|
||||
checkUpdate();
|
||||
setShowUpdateSnackbar(true);
|
||||
}}>
|
||||
<TouchableOpacity onPress={checkUpdate}>
|
||||
<Text style={styles.instructions}>点击这里检查更新</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
@@ -89,7 +83,7 @@ function App() {
|
||||
<TestConsole visible={showTestConsole} />
|
||||
{snackbarVisible && (
|
||||
<Snackbar
|
||||
visible={snackbarVisible}
|
||||
visible={true}
|
||||
onDismiss={() => {
|
||||
setShowUpdateSnackbar(false);
|
||||
}}
|
||||
@@ -101,13 +95,10 @@ function App() {
|
||||
setShowUpdateBanner(true);
|
||||
},
|
||||
}}>
|
||||
<Text style={{color: 'white'}}>
|
||||
有新版本({updateInfo.name})可用,是否更新?
|
||||
</Text>
|
||||
<Text>有新版本({updateInfo.version})可用,是否更新?</Text>
|
||||
</Snackbar>
|
||||
)}
|
||||
<Banner
|
||||
style={{width: '100%', position: 'absolute', top: 0}}
|
||||
visible={showUpdateBanner}
|
||||
actions={[
|
||||
{
|
||||
|
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"ios": {
|
||||
"appId": 24794,
|
||||
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
|
||||
},
|
||||
"android": {
|
||||
"appId": 27509,
|
||||
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
|
||||
}
|
||||
"ios": {
|
||||
"appId": 24794,
|
||||
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
|
||||
},
|
||||
"android": {
|
||||
"appId": 10977,
|
||||
"appKey": "bUYKfZgtC9VirZsQbAt8qken2Gq2uxe3"
|
||||
}
|
||||
}
|
@@ -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.0.0-beta.1:
|
||||
version "10.0.0-beta.1"
|
||||
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.0-beta.1.tgz#bc49a7197dd19c16ba798ea13324b4b292edd052"
|
||||
integrity sha512-PFTsut8SL+vqAPtBUzPg9KKU9mFgCktKttifzM8B4puSoburlSN2UnD+eDWxLkXyIWQtoQAqAmXPE1/zA/e7dw==
|
||||
dependencies:
|
||||
nanoid "^3.3.3"
|
||||
|
||||
|
@@ -166,6 +166,13 @@ 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,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) {
|
||||
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 NativePushySpec {
|
||||
public class UpdateModule extends NativeUpdateSpec {
|
||||
UpdateContext updateContext;
|
||||
public static ReactApplicationContext mContext;
|
||||
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
|
||||
@@ -108,6 +108,11 @@ public class UpdateModule extends NativePushySpec {
|
||||
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);
|
||||
|
@@ -239,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
|
||||
public void setUuid(final String uuid) {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
|
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
presets: ['module:@react-native/babel-preset'],
|
||||
};
|
@@ -192,6 +192,24 @@ 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)
|
||||
{
|
||||
|
23
package.json
23
package.json
@@ -1,11 +1,10 @@
|
||||
{
|
||||
"name": "react-native-update",
|
||||
"version": "10.3.0",
|
||||
"version": "10.0.0-beta.2",
|
||||
"description": "react-native hot update",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"prepack": "yarn submodule && yarn lint",
|
||||
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
|
||||
"prepublish": "yarn submodule",
|
||||
"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",
|
||||
@@ -48,25 +47,25 @@
|
||||
"nanoid": "^3.3.3"
|
||||
},
|
||||
"codegenConfig": {
|
||||
"name": "RCTPushySpec",
|
||||
"type": "modules",
|
||||
"jsSrcsDir": "src"
|
||||
"libraries": [
|
||||
{
|
||||
"name": "RCTPushySpec",
|
||||
"type": "modules",
|
||||
"jsSrcsDir": "lib"
|
||||
}
|
||||
]
|
||||
},
|
||||
"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.57.0",
|
||||
"eslint-plugin-ft-flow": "^3.0.7",
|
||||
"eslint": "^8.56.0",
|
||||
"firebase-tools": "^11.24.1",
|
||||
"fs-extra": "^9.1.0",
|
||||
"jest": "^29.7.0",
|
||||
"jest": "^29.2.1",
|
||||
"pod-install": "^0.1.37",
|
||||
"prettier": "^2",
|
||||
"react": "18.2.0",
|
||||
|
118
src/client.tsx
118
src/client.tsx
@@ -1,5 +1,5 @@
|
||||
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
|
||||
import { assertRelease, log, testUrls } from './utils';
|
||||
import { CheckResult, PushyOptions, ProgressData } from './type';
|
||||
import { assertRelease, log } from './utils';
|
||||
import {
|
||||
EmitterSubscription,
|
||||
PermissionsAndroid,
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
pushyNativeEventEmitter,
|
||||
currentVersion,
|
||||
packageVersion,
|
||||
report,
|
||||
rolledBackVersion,
|
||||
setLocalHashInfo,
|
||||
isRolledBack,
|
||||
} from './core';
|
||||
|
||||
const defaultServer = {
|
||||
@@ -25,23 +25,19 @@ const defaultServer = {
|
||||
};
|
||||
|
||||
const empty = {};
|
||||
const noop = () => {};
|
||||
|
||||
export class Pushy {
|
||||
options: PushyOptions = {
|
||||
appKey: '',
|
||||
server: defaultServer,
|
||||
autoMarkSuccess: true,
|
||||
useAlert: true,
|
||||
strategy: 'both',
|
||||
logger: noop,
|
||||
};
|
||||
|
||||
lastChecking?: number;
|
||||
lastRespJson?: Promise<any>;
|
||||
lastChecking: number;
|
||||
lastResult: CheckResult;
|
||||
|
||||
progressHandlers: Record<string, EmitterSubscription> = {};
|
||||
downloadedHash?: string;
|
||||
downloadedHash: string;
|
||||
|
||||
marked = false;
|
||||
applyingUpdate = false;
|
||||
@@ -57,47 +53,11 @@ export class Pushy {
|
||||
setOptions = (options: Partial<PushyOptions>) => {
|
||||
for (const [key, value] of Object.entries(options)) {
|
||||
if (value !== undefined) {
|
||||
// @ts-expect-error
|
||||
this.options[key] = value;
|
||||
if (key === 'logger') {
|
||||
if (isRolledBack) {
|
||||
this.report({
|
||||
type: 'rollback',
|
||||
data: {
|
||||
rolledBackVersion,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
report = ({
|
||||
type,
|
||||
message = '',
|
||||
data = {},
|
||||
}: {
|
||||
type: EventType;
|
||||
message?: string;
|
||||
data?: Record<string, string | number>;
|
||||
}) => {
|
||||
log(type + ' ' + message);
|
||||
const { logger = noop, appKey } = this.options;
|
||||
logger({
|
||||
type,
|
||||
data: {
|
||||
appKey,
|
||||
currentVersion,
|
||||
cInfo,
|
||||
packageVersion,
|
||||
buildTime,
|
||||
message,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
getCheckUrl = (endpoint: string = this.options.server!.main) => {
|
||||
return `${endpoint}/checkUpdate/${this.options.appKey}`;
|
||||
};
|
||||
@@ -118,7 +78,7 @@ export class Pushy {
|
||||
}
|
||||
this.marked = true;
|
||||
PushyModule.markSuccess();
|
||||
this.report({ type: 'markSuccess' });
|
||||
report({ type: 'markSuccess' });
|
||||
};
|
||||
switchVersion = (hash: string) => {
|
||||
assertRelease();
|
||||
@@ -140,14 +100,14 @@ export class Pushy {
|
||||
assertRelease();
|
||||
const now = Date.now();
|
||||
if (
|
||||
this.lastRespJson &&
|
||||
this.lastResult &&
|
||||
this.lastChecking &&
|
||||
now - this.lastChecking < 1000 * 5
|
||||
) {
|
||||
return await this.lastRespJson;
|
||||
return this.lastResult;
|
||||
}
|
||||
this.lastChecking = now;
|
||||
this.report({ type: 'checking' });
|
||||
report({ type: 'checking' });
|
||||
const fetchPayload = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -164,8 +124,8 @@ export class Pushy {
|
||||
let resp;
|
||||
try {
|
||||
resp = await fetch(this.getCheckUrl(), fetchPayload);
|
||||
} catch (e: any) {
|
||||
this.report({
|
||||
} catch (e) {
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
message: 'Can not connect to update server. Trying backup endpoints.',
|
||||
});
|
||||
@@ -173,7 +133,7 @@ export class Pushy {
|
||||
if (backupEndpoints) {
|
||||
try {
|
||||
resp = await Promise.race(
|
||||
backupEndpoints.map(endpoint =>
|
||||
backupEndpoints.map((endpoint) =>
|
||||
fetch(this.getCheckUrl(endpoint), fetchPayload),
|
||||
),
|
||||
);
|
||||
@@ -181,18 +141,18 @@ export class Pushy {
|
||||
}
|
||||
}
|
||||
if (!resp) {
|
||||
this.report({
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
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) {
|
||||
this.report({
|
||||
report({
|
||||
type: 'errorChecking',
|
||||
message: result.message,
|
||||
});
|
||||
@@ -215,7 +175,7 @@ export class Pushy {
|
||||
new Set([...(server.backups || []), ...remoteEndpoints]),
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
log('failed to fetch endpoints from: ', server.queryUrl);
|
||||
}
|
||||
}
|
||||
@@ -226,18 +186,8 @@ export class Pushy {
|
||||
onDownloadProgress?: (data: ProgressData) => void,
|
||||
) => {
|
||||
assertRelease();
|
||||
const {
|
||||
hash,
|
||||
diffUrl: _diffUrl,
|
||||
diffUrls,
|
||||
pdiffUrl: _pdiffUrl,
|
||||
pdiffUrls,
|
||||
updateUrl: _updateUrl,
|
||||
updateUrls,
|
||||
name,
|
||||
description,
|
||||
metaInfo,
|
||||
} = info;
|
||||
const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
|
||||
info;
|
||||
if (!info.update || !hash) {
|
||||
return;
|
||||
}
|
||||
@@ -255,7 +205,7 @@ export class Pushy {
|
||||
if (onDownloadProgress) {
|
||||
this.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
|
||||
'RCTPushyDownloadProgress',
|
||||
progressData => {
|
||||
(progressData) => {
|
||||
if (progressData.hash === hash) {
|
||||
onDownloadProgress(progressData);
|
||||
}
|
||||
@@ -263,8 +213,7 @@ export class Pushy {
|
||||
);
|
||||
}
|
||||
let succeeded = false;
|
||||
this.report({ type: 'downloading' });
|
||||
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
|
||||
report({ type: 'downloading' });
|
||||
if (diffUrl) {
|
||||
log('downloading diff');
|
||||
try {
|
||||
@@ -274,11 +223,10 @@ export class Pushy {
|
||||
originHash: currentVersion,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
}
|
||||
}
|
||||
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
|
||||
if (!succeeded && pdiffUrl) {
|
||||
log('downloading pdiff');
|
||||
try {
|
||||
@@ -287,11 +235,10 @@ export class Pushy {
|
||||
hash,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
}
|
||||
}
|
||||
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
|
||||
if (!succeeded && updateUrl) {
|
||||
log('downloading full patch');
|
||||
try {
|
||||
@@ -300,7 +247,7 @@ export class Pushy {
|
||||
hash,
|
||||
});
|
||||
succeeded = true;
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
log(`full patch error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
@@ -309,12 +256,11 @@ export class Pushy {
|
||||
delete this.progressHandlers[hash];
|
||||
}
|
||||
if (!succeeded) {
|
||||
return this.report({
|
||||
return report({
|
||||
type: 'errorUpdate',
|
||||
data: { newVersion: hash },
|
||||
});
|
||||
}
|
||||
log('downloaded hash:', hash);
|
||||
setLocalHashInfo(hash, {
|
||||
name,
|
||||
description,
|
||||
@@ -330,17 +276,17 @@ export class Pushy {
|
||||
if (Platform.OS !== 'android') {
|
||||
return;
|
||||
}
|
||||
this.report({ type: 'downloadingApk' });
|
||||
report({ type: 'downloadingApk' });
|
||||
if (Platform.Version <= 23) {
|
||||
try {
|
||||
const granted = await PermissionsAndroid.request(
|
||||
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
|
||||
);
|
||||
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
|
||||
return this.report({ type: 'rejectStoragePermission' });
|
||||
return report({ type: 'rejectStoragePermission' });
|
||||
}
|
||||
} catch (e: any) {
|
||||
return this.report({ type: 'errorStoragePermission' });
|
||||
} catch (err) {
|
||||
return report({ type: 'errorStoragePermission' });
|
||||
}
|
||||
}
|
||||
const progressKey = 'downloadingApk';
|
||||
@@ -359,7 +305,7 @@ export class Pushy {
|
||||
target: 'update.apk',
|
||||
hash: progressKey,
|
||||
}).catch(() => {
|
||||
this.report({ type: 'errowDownloadAndInstallApk' });
|
||||
report({ type: 'errowDownloadAndInstallApk' });
|
||||
});
|
||||
if (this.progressHandlers[progressKey]) {
|
||||
this.progressHandlers[progressKey].remove();
|
||||
|
@@ -2,35 +2,27 @@ import { createContext, useContext } from 'react';
|
||||
import { CheckResult, ProgressData } from './type';
|
||||
import { Pushy } from './client';
|
||||
|
||||
const empty = {};
|
||||
const noop = () => {};
|
||||
const asyncNoop = () => Promise.resolve();
|
||||
|
||||
export const defaultContext = {
|
||||
checkUpdate: asyncNoop,
|
||||
checkUpdate: () => Promise.resolve(empty),
|
||||
switchVersion: noop,
|
||||
switchVersionLater: noop,
|
||||
markSuccess: noop,
|
||||
dismissError: noop,
|
||||
downloadUpdate: asyncNoop,
|
||||
downloadAndInstallApk: asyncNoop,
|
||||
getCurrentVersionInfo: () => Promise.resolve({}),
|
||||
downloadUpdate: noop,
|
||||
currentHash: '',
|
||||
packageVersion: '',
|
||||
};
|
||||
|
||||
export const PushyContext = createContext<{
|
||||
checkUpdate: () => Promise<void>;
|
||||
checkUpdate: () => void;
|
||||
switchVersion: () => void;
|
||||
switchVersionLater: () => void;
|
||||
markSuccess: () => void;
|
||||
dismissError: () => void;
|
||||
downloadUpdate: () => Promise<void>;
|
||||
downloadAndInstallApk: (url: string) => Promise<void>;
|
||||
getCurrentVersionInfo: () => Promise<{
|
||||
name?: string;
|
||||
description?: string;
|
||||
metaInfo?: string;
|
||||
}>;
|
||||
downloadUpdate: () => void;
|
||||
currentHash: string;
|
||||
packageVersion: string;
|
||||
client?: Pushy;
|
||||
|
45
src/core.ts
45
src/core.ts
@@ -1,15 +1,14 @@
|
||||
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
|
||||
import { EventType, UpdateEventsLogger } from './type';
|
||||
import { log } from './utils';
|
||||
const {
|
||||
version: v,
|
||||
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
||||
const isTurboModuleEnabled =
|
||||
// @ts-expect-error
|
||||
global.__turboModuleProxy != null;
|
||||
const isTurboModuleEnabled = global.__turboModuleProxy != null;
|
||||
|
||||
export const PushyModule = isTurboModuleEnabled
|
||||
? require('./NativePushy').default
|
||||
? require('./turboModuleSpec').default
|
||||
: NativeModules.Pushy;
|
||||
|
||||
if (!PushyModule) {
|
||||
@@ -59,6 +58,44 @@ if (!uuid) {
|
||||
PushyModule.setUuid(uuid);
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
let reporter: UpdateEventsLogger = noop;
|
||||
|
||||
export function onPushyEvents(customReporter: UpdateEventsLogger) {
|
||||
reporter = customReporter;
|
||||
if (isRolledBack) {
|
||||
report({
|
||||
type: 'rollback',
|
||||
data: {
|
||||
rolledBackVersion,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function report({
|
||||
type,
|
||||
message = '',
|
||||
data = {},
|
||||
}: {
|
||||
type: EventType;
|
||||
message?: string;
|
||||
data?: Record<string, string | number>;
|
||||
}) {
|
||||
log(type + ' ' + message);
|
||||
reporter({
|
||||
type,
|
||||
data: {
|
||||
currentVersion,
|
||||
cInfo,
|
||||
packageVersion,
|
||||
buildTime,
|
||||
message,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
log('uuid: ' + uuid);
|
||||
|
||||
export const cInfo = {
|
||||
|
132
src/provider.tsx
132
src/provider.tsx
@@ -13,13 +13,8 @@ import {
|
||||
Linking,
|
||||
} from 'react-native';
|
||||
import { Pushy } from './client';
|
||||
import {
|
||||
currentVersion,
|
||||
isFirstTime,
|
||||
packageVersion,
|
||||
getCurrentVersionInfo,
|
||||
} from './core';
|
||||
import { CheckResult, ProgressData } from './type';
|
||||
import { currentVersion, isFirstTime, packageVersion } from './core';
|
||||
import { CheckResult } from './type';
|
||||
import { PushyContext } from './context';
|
||||
|
||||
export const PushyProvider = ({
|
||||
@@ -29,25 +24,24 @@ export const PushyProvider = ({
|
||||
client: Pushy;
|
||||
children: ReactNode;
|
||||
}) => {
|
||||
const { options } = client;
|
||||
const { strategy, useAlert } = client.options;
|
||||
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);
|
||||
}, []);
|
||||
if (lastError) {
|
||||
setLastError(undefined);
|
||||
}
|
||||
}, [lastError]);
|
||||
|
||||
const showAlert = useCallback(
|
||||
(...args: Parameters<typeof Alert.alert>) => {
|
||||
if (options.useAlert) {
|
||||
if (useAlert) {
|
||||
Alert.alert(...args);
|
||||
}
|
||||
},
|
||||
[options],
|
||||
[useAlert],
|
||||
);
|
||||
|
||||
const switchVersion = useCallback(() => {
|
||||
@@ -62,65 +56,47 @@ export const PushyProvider = ({
|
||||
}
|
||||
}, [client, updateInfo]);
|
||||
|
||||
const downloadUpdate = useCallback(
|
||||
async (info: CheckResult | undefined = updateInfoRef.current) => {
|
||||
if (!info || !info.update) {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
},
|
||||
},
|
||||
]);
|
||||
} catch (e: any) {
|
||||
setLastError(e);
|
||||
showAlert('更新失败', e.message);
|
||||
}
|
||||
},
|
||||
[client, showAlert],
|
||||
);
|
||||
|
||||
const downloadAndInstallApk = useCallback(
|
||||
async (downloadUrl: string) => {
|
||||
if (Platform.OS === 'android' && downloadUrl) {
|
||||
await client.downloadAndInstallApk(downloadUrl, setProgress);
|
||||
}
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
const checkUpdate = useCallback(async () => {
|
||||
const now = Date.now();
|
||||
if (lastChecking.current && now - lastChecking.current < 1000) {
|
||||
const downloadUpdate = useCallback(async () => {
|
||||
if (!updateInfo || !updateInfo.update) {
|
||||
return;
|
||||
}
|
||||
lastChecking.current = now;
|
||||
try {
|
||||
const hash = await client.downloadUpdate(updateInfo);
|
||||
if (!hash) {
|
||||
return;
|
||||
}
|
||||
stateListener.current && stateListener.current.remove();
|
||||
showAlert('提示', '下载完毕,是否立即更新?', [
|
||||
{
|
||||
text: '下次再说',
|
||||
style: 'cancel',
|
||||
onPress: () => {
|
||||
client.switchVersionLater(hash);
|
||||
},
|
||||
},
|
||||
{
|
||||
text: '立即更新',
|
||||
style: 'default',
|
||||
onPress: () => {
|
||||
client.switchVersion(hash);
|
||||
},
|
||||
},
|
||||
]);
|
||||
} catch (err) {
|
||||
setLastError(err);
|
||||
showAlert('更新失败', err.message);
|
||||
}
|
||||
}, [client, showAlert, updateInfo]);
|
||||
|
||||
const checkUpdate = useCallback(async () => {
|
||||
let info: CheckResult;
|
||||
try {
|
||||
info = await client.checkUpdate();
|
||||
} catch (e: any) {
|
||||
setLastError(e);
|
||||
showAlert('更新检查失败', e.message);
|
||||
} catch (err) {
|
||||
setLastError(err);
|
||||
showAlert('更新检查失败', err.message);
|
||||
return;
|
||||
}
|
||||
updateInfoRef.current = info;
|
||||
setUpdateInfo(info);
|
||||
if (info.expired) {
|
||||
const { downloadUrl } = info;
|
||||
@@ -130,7 +106,7 @@ export const PushyProvider = ({
|
||||
onPress: () => {
|
||||
if (downloadUrl) {
|
||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||
downloadAndInstallApk(downloadUrl);
|
||||
client.downloadAndInstallApk(downloadUrl);
|
||||
} else {
|
||||
Linking.openURL(downloadUrl);
|
||||
}
|
||||
@@ -154,23 +130,18 @@ export const PushyProvider = ({
|
||||
],
|
||||
);
|
||||
}
|
||||
}, [client, downloadAndInstallApk, downloadUpdate, showAlert]);
|
||||
}, [client, downloadUpdate, showAlert]);
|
||||
|
||||
const markSuccess = client.markSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (__DEV__) {
|
||||
console.info('检测到在DEV环境,不会进行热更新检查');
|
||||
return;
|
||||
}
|
||||
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||
if (isFirstTime && autoMarkSuccess) {
|
||||
if (isFirstTime) {
|
||||
markSuccess();
|
||||
}
|
||||
if (strategy === 'both' || strategy === 'onAppResume') {
|
||||
stateListener.current = AppState.addEventListener(
|
||||
'change',
|
||||
nextAppState => {
|
||||
(nextAppState) => {
|
||||
if (nextAppState === 'active') {
|
||||
checkUpdate();
|
||||
}
|
||||
@@ -181,6 +152,7 @@ export const PushyProvider = ({
|
||||
checkUpdate();
|
||||
}
|
||||
let dismissErrorTimer: ReturnType<typeof setTimeout>;
|
||||
const { dismissErrorAfter } = client.options;
|
||||
if (typeof dismissErrorAfter === 'number' && dismissErrorAfter > 0) {
|
||||
dismissErrorTimer = setTimeout(() => {
|
||||
dismissError();
|
||||
@@ -190,7 +162,7 @@ export const PushyProvider = ({
|
||||
stateListener.current && stateListener.current.remove();
|
||||
clearTimeout(dismissErrorTimer);
|
||||
};
|
||||
}, [checkUpdate, options, dismissError, markSuccess]);
|
||||
}, [checkUpdate, client.options, dismissError, markSuccess, strategy]);
|
||||
|
||||
return (
|
||||
<PushyContext.Provider
|
||||
@@ -206,10 +178,8 @@ export const PushyProvider = ({
|
||||
downloadUpdate,
|
||||
packageVersion,
|
||||
currentHash: currentVersion,
|
||||
progress,
|
||||
downloadAndInstallApk,
|
||||
getCurrentVersionInfo,
|
||||
}}>
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PushyContext.Provider>
|
||||
);
|
||||
|
@@ -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 {
|
||||
getConstants: () => {
|
@@ -8,11 +8,8 @@ export interface CheckResult {
|
||||
description?: string;
|
||||
metaInfo?: string;
|
||||
pdiffUrl?: string;
|
||||
pdiffUrls?: string[];
|
||||
diffUrl?: string;
|
||||
diffUrls?: string[];
|
||||
updateUrl?: string;
|
||||
updateUrls?: string[];
|
||||
paused?: 'app' | 'package';
|
||||
message?: string;
|
||||
}
|
||||
|
19
src/utils.ts
19
src/utils.ts
@@ -7,22 +7,3 @@ export function assertRelease() {
|
||||
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
|
||||
}
|
||||
}
|
||||
|
||||
const ping = async (url: string) =>
|
||||
Promise.race([
|
||||
fetch(url, {
|
||||
method: 'HEAD',
|
||||
}).then(({ status }) => status === 200),
|
||||
new Promise<false>(r => setTimeout(() => r(false), 2000)),
|
||||
]);
|
||||
|
||||
const canUseGoogle = ping('https://www.google.com');
|
||||
|
||||
export const testUrls = async (urls?: string[]) => {
|
||||
if (!urls?.length || (await canUseGoogle)) {
|
||||
return null;
|
||||
}
|
||||
return Promise.race(urls.map(url => ping(url).then(() => url))).catch(
|
||||
() => null,
|
||||
);
|
||||
};
|
||||
|
6
tea.yaml
6
tea.yaml
@@ -1,6 +0,0 @@
|
||||
# https://tea.xyz/what-is-this-file
|
||||
---
|
||||
version: 1.0.0
|
||||
codeOwners:
|
||||
- '0x10D90dC0034E2e82F0AC55954B3ed4EC0550ECe7'
|
||||
quorum: 1
|
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"extends": "@react-native/typescript-config/tsconfig.json",
|
||||
"include": ["src/**/*"]
|
||||
}
|
Reference in New Issue
Block a user