1
0
mirror of https://gitcode.com/gh_mirrors/re/react-native-pushy.git synced 2025-11-23 07:53:38 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

21 Commits

Author SHA1 Message Date
sunnylqm
dc9b5d722a Refactor UpdateContext to implement singleton pattern and ensure synchronous SharedPreferences writes. Update UpdateModule constructors to utilize the singleton instance. 2025-11-19 18:58:00 +08:00
sunnylqm
e151c9c618 Enhance useUpdate hook to validate context usage and add error messages for out-of-provider usage in English and Chinese locales. 2025-11-18 20:19:06 +08:00
sunnylqm
2a79061b89 Remove cross-version update support from README comparison table for hot update libraries. 2025-11-12 18:36:15 +08:00
sunnylqm
e04ce54de6 Update README with comparison table for hot update libraries and adjust package references in JSON files for pushy. Bump react-native-update version to 10.35.7 in relevant files. 2025-11-12 18:33:16 +08:00
sunnylqm
38229a8bca update react-native-update version from 10.35.6 to 10.35.7 in package.json and bun.lock 2025-11-04 19:54:54 +08:00
Sunny Luo
6661e307cd Update package.json 2025-10-31 13:18:42 +08:00
Scc
027bd16af2 fix: expected ';' at end of declaration (#515) 2025-10-31 13:18:24 +08:00
sunnylqm
4daaadce70 refactor hvigor-plugin to use 2-space indentation for JSON and improve condition checks in RCTPushy 2025-10-30 00:01:26 +08:00
sunnylqm
43ed2f50fe update react-native-update version from 10.35.2 to 10.35.4 in package.json and bun.lock 2025-10-27 12:04:01 +08:00
sunnylqm
e46d01714a fix patchfromppk 2025-10-27 10:16:59 +08:00
sunnylqm
366b2a6618 fix harmony copies 2025-10-27 00:46:21 +08:00
sunnylqm
34e053ae48 update react-native-update version from 10.35.2 to 10.35.3 in package.json and remove lastVersion from shared preferences in UpdateContext.java 2025-10-26 23:51:58 +08:00
sunnylqm
d55ef1d8c8 update react-native-update version from 10.35.1 to 10.35.2 in package.json and bun.lock 2025-10-26 23:27:24 +08:00
sunnylqm
de3e7d9e4c decrement version in package.json from 10.35.3 to 10.35.2 2025-10-26 23:12:29 +08:00
sunnylqm
e0201d3882 fix hvigor plugin 2025-10-26 23:10:44 +08:00
sunnylqm
ba5b35813d fix unzip 2025-10-25 00:59:12 +08:00
sunnylqm
3134f36739 update example dep 2025-10-24 23:01:50 +08:00
sunnylqm
d4f4740053 update lock 2025-10-24 22:52:15 +08:00
sunnylqm
a248f18035 use latest rnoh package 2025-10-24 22:51:07 +08:00
sunnylqm
268f39f43b fix filejsbundleprovider 2025-10-24 22:09:05 +08:00
sunnylqm
6e4f432e26 fix 2025-10-24 17:01:50 +08:00
35 changed files with 665 additions and 1035 deletions

1
.gitignore vendored
View File

@@ -59,3 +59,4 @@ harmony/package
harmony/pushy/.preview harmony/pushy/.preview
Example/harmony_use_pushy/harmony/entry/src/main/resources/rawfile/meta.json Example/harmony_use_pushy/harmony/entry/src/main/resources/rawfile/meta.json
**/.hvigor **/.hvigor
Example/harmony_use_pushy/harmony/entry/src/main/cpp/generated

View File

@@ -1,4 +1,3 @@
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */ /* eslint-disable react-native/no-inline-styles */
import React, {useState} from 'react'; import React, {useState} from 'react';
import {StyleSheet, Text, View, TouchableOpacity, Image} from 'react-native'; import {StyleSheet, Text, View, TouchableOpacity, Image} from 'react-native';
@@ -6,7 +5,7 @@ import {StyleSheet, Text, View, TouchableOpacity, Image} from 'react-native';
import TestConsole from './TestConsole'; import TestConsole from './TestConsole';
import _updateConfig from './update.json'; import _updateConfig from './update.json';
import {PushyProvider, Pushy, usePushy} from 'react-native-update'; import {UpdateProvider, Pushy, useUpdate} from 'react-native-update';
const {appKey} = _updateConfig.harmony; const {appKey} = _updateConfig.harmony;
function App() { function App() {
@@ -20,7 +19,7 @@ function App() {
packageVersion, packageVersion,
currentHash, currentHash,
progress: {received, total} = {}, progress: {received, total} = {},
} = usePushy(); } = useUpdate();
const [useDefaultAlert, setUseDefaultAlert] = useState(false); const [useDefaultAlert, setUseDefaultAlert] = useState(false);
const [showTestConsole, setShowTestConsole] = useState(false); const [showTestConsole, setShowTestConsole] = useState(false);
const [showUpdateBanner, setShowUpdateBanner] = useState(false); const [showUpdateBanner, setShowUpdateBanner] = useState(false);
@@ -41,6 +40,7 @@ function App() {
return ( return (
<View style={styles.container}> <View style={styles.container}>
<Text style={styles.welcome}>使Pushy热更新服务</Text> <Text style={styles.welcome}>使Pushy热更新服务</Text>
{/* <Image source={require('./gmail.png')} style={styles.image} /> */}
{/* <Text style={styles.welcome}>😁hdiffFromAPP更新成功</Text> */} {/* <Text style={styles.welcome}>😁hdiffFromAPP更新成功</Text> */}
{/* <Text style={styles.welcome}>😁hdiffFromPPk更新成功</Text> */} {/* <Text style={styles.welcome}>😁hdiffFromPPk更新成功</Text> */}
<View style={{flexDirection: 'row'}}> <View style={{flexDirection: 'row'}}>
@@ -166,7 +166,7 @@ function App() {
style={{marginRight: 20}}> style={{marginRight: 20}}>
<Text style={{color: '#2196F3'}}></Text> <Text style={{color: '#2196F3'}}></Text>
</TouchableOpacity> </TouchableOpacity>
<TouchableOpacity onPress={switchVersion}> <TouchableOpacity onPress={() => switchVersion()}>
<Text style={{color: '#2196F3'}}></Text> <Text style={{color: '#2196F3'}}></Text>
</TouchableOpacity> </TouchableOpacity>
</View> </View>
@@ -204,18 +204,22 @@ const styles = StyleSheet.create({
color: '#333333', color: '#333333',
marginBottom: 5, marginBottom: 5,
}, },
image: {}, image: {
width: 109,
height: 40,
},
}); });
const pushyClient = new Pushy({ const pushyClient = new Pushy({
appKey, appKey,
debug: true, debug: true,
updateStrategy: null,
}); });
export default function Root() { export default function Root() {
return ( return (
<PushyProvider client={pushyClient}> <UpdateProvider client={pushyClient}>
<App /> <App />
</PushyProvider> </UpdateProvider>
); );
} }

View File

@@ -1,6 +0,0 @@
source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby ">= 2.6.10"
gem 'cocoapods', '~> 1.12'

File diff suppressed because it is too large Load Diff

View File

@@ -10,8 +10,9 @@
buildOption: { buildOption: {
strictMode: { strictMode: {
caseSensitiveCheck: true, caseSensitiveCheck: true,
useNormalizedOHMUrl: true, useNormalizedOHMUrl: true
}, },
"nativeCompiler": "BiSheng"
}, },
}, },
], ],

View File

@@ -1,44 +1,9 @@
import { hapTasks } from '@ohos/hvigor-ohos-plugin'; import {hapTasks} from '@ohos/hvigor-ohos-plugin';
import fs from 'fs'; import {reactNativeUpdatePlugin} from 'pushy/hvigor-plugin';
import path from 'path';
export function generatePushyBuildTime(str?: string) {
return {
pluginId: 'PushyBuildTimePlugin',
apply(pluginContext) {
pluginContext.registerTask({
name: 'pushy_build_time',
run: (taskContext) => {
const metaFilePath = path.resolve(__dirname, 'src/main/resources/rawfile/meta.json');
const dirPath = path.dirname(metaFilePath);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const moduleJsonPath = path.resolve(__dirname, '../AppScope/app.json5');
let versionName = '';
if (fs.existsSync(moduleJsonPath)) {
const moduleContent = fs.readFileSync(moduleJsonPath, 'utf-8');
const versionMatch = moduleContent.match(/"versionName":\s*"([^"]+)"/);
if (versionMatch && versionMatch[1]) {
versionName = versionMatch[1];
}
}
const buildTime = new Date().toISOString();
const metaContent = {
pushy_build_time: buildTime,
versionName: versionName
};
fs.writeFileSync(metaFilePath, JSON.stringify(metaContent, null, 4));
console.log(`Build time written to ${metaFilePath}`);
},
dependencies: [],
postDependencies: ['default@BuildJS']
})
}
}
}
export default { export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ system: hapTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
plugins:[generatePushyBuildTime()] /* Custom plugin to extend the functionality of Hvigor. */ plugins: [
} reactNativeUpdatePlugin(),
] /* Custom plugin to extend the functionality of Hvigor. */,
};

View File

@@ -6,15 +6,15 @@
"lockfileVersion": 3, "lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": { "specifiers": {
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38", "@rnoh/react-native-openharmony@0.72.96": "@rnoh/react-native-openharmony@0.72.96",
"pushy@../../node_modules/react-native-update/harmony/pushy": "pushy@../../node_modules/react-native-update/harmony/pushy" "pushy@../../node_modules/react-native-update/harmony/pushy": "pushy@../../node_modules/react-native-update/harmony/pushy"
}, },
"packages": { "packages": {
"@rnoh/react-native-openharmony@0.72.38": { "@rnoh/react-native-openharmony@0.72.96": {
"name": "", "name": "",
"version": "0.72.38", "version": "0.72.96",
"integrity": "sha512-br5SIrbB0OarSLirenleE7eTOX1lNccMJ7nb/G7qWTyJ7kW4DalmTXVKYpoT2qaOLls1uEE7McD1OjbZZM9jug==", "integrity": "sha512-gBbm8LLyqi5UE7qHWdZYeQnjyncfEpCczKZUP/9M2U1Z7exR0Kya8PMKMwr1ta5ujy7w/hZVC2LomEV4QvBeqA==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.38.har", "resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.96.har",
"registryType": "ohpm" "registryType": "ohpm"
}, },
"pushy@../../node_modules/react-native-update/harmony/pushy": { "pushy@../../node_modules/react-native-update/harmony/pushy": {

View File

@@ -6,7 +6,7 @@
author: '', author: '',
license: '', license: '',
dependencies: { dependencies: {
'@rnoh/react-native-openharmony': '0.72.38', '@rnoh/react-native-openharmony': '0.72.96',
pushy: 'file:../../node_modules/react-native-update/harmony/pushy', pushy: 'file:../../node_modules/react-native-update/harmony/pushy',
}, },
} }

View File

@@ -1,65 +0,0 @@
/**
* This code was generated by "react-native codegen-harmony"
*
* Do not edit this file as changes may cause incorrect behavior and will be
* lost once the code is regenerated.
*
* @generatorVersion: 1
*/
#pragma once
#include "RNOH/Package.h"
#include "RNOH/ArkTSTurboModule.h"
namespace rnoh {
class RNOHGeneratedPackageTurboModuleFactoryDelegate : public TurboModuleFactoryDelegate {
public:
SharedTurboModule createTurboModule(Context ctx, const std::string &name) const override {
return nullptr;
};
};
class GeneratedEventEmitRequestHandler : public EventEmitRequestHandler {
public:
void handleEvent(Context const &ctx) override {
auto eventEmitter = ctx.shadowViewRegistry->getEventEmitter<facebook::react::EventEmitter>(ctx.tag);
if (eventEmitter == nullptr) {
return;
}
std::vector<std::string> supportedEventNames = {
};
if (std::find(supportedEventNames.begin(), supportedEventNames.end(), ctx.eventName) != supportedEventNames.end()) {
eventEmitter->dispatchEvent(ctx.eventName, ArkJS(ctx.env).getDynamic(ctx.payload));
}
}
};
class RNOHGeneratedPackage : public Package {
public:
RNOHGeneratedPackage(Package::Context ctx) : Package(ctx){};
std::unique_ptr<TurboModuleFactoryDelegate> createTurboModuleFactoryDelegate() override {
return std::make_unique<RNOHGeneratedPackageTurboModuleFactoryDelegate>();
}
std::vector<facebook::react::ComponentDescriptorProvider> createComponentDescriptorProviders() override {
return {
};
}
ComponentJSIBinderByString createComponentJSIBinderByName() override {
return {
};
};
EventEmitRequestHandlers createEventEmitRequestHandlers() override {
return {
std::make_shared<GeneratedEventEmitRequestHandler>(),
};
}
};
} // namespace rnoh

View File

@@ -54,7 +54,6 @@ struct Index {
enableCAPIArchitecture: true, enableCAPIArchitecture: true,
arkTsComponentNames: arkTsComponentNames, arkTsComponentNames: arkTsComponentNames,
}, },
initialProps: { "foo": "bar" } as Record<string, string>,
appKey: "harmony_use_pushy", appKey: "harmony_use_pushy",
wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder, wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
onSetUp: (rnInstance) => { onSetUp: (rnInstance) => {

File diff suppressed because one or more lines are too long

View File

@@ -1,6 +1,7 @@
{ {
"modelVersion": "5.0.0", "modelVersion": "5.0.0",
"dependencies": { "dependencies": {
pushy: 'file:../../node_modules/react-native-update/harmony/pushy'
}, },
"execution": { "execution": {
// "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */ // "analyze": "normal", /* Define the build analyze mode. Value: [ "normal" | "advanced" | false ]. Default: "normal" */

View File

@@ -13,6 +13,6 @@
}, },
}, },
overrides: { overrides: {
'@rnoh/react-native-openharmony': '0.72.38', '@rnoh/react-native-openharmony': '0.72.96',
}, },
} }

View File

@@ -8,7 +8,7 @@
"lint": "eslint .", "lint": "eslint .",
"start": "npm run codegen && hdc rport tcp:8081 tcp:8081 && react-native start", "start": "npm run codegen && hdc rport tcp:8081 tcp:8081 && react-native start",
"codegen": "react-native codegen-harmony --rnoh-module-path ./harmony/react_native_openharmony", "codegen": "react-native codegen-harmony --rnoh-module-path ./harmony/react_native_openharmony",
"build": "pushy bundle --platform harmony", "build": "pushy bundle --platform harmony --no-interactive",
"test": "jest", "test": "jest",
"hdiffFromPPK": "pushy hdiffFromPPK .pushy/output/harmony.1735052610653.ppk .pushy/output/harmony.1735052678646.ppk .pushy/output/hdiff.ppk-patch", "hdiffFromPPK": "pushy hdiffFromPPK .pushy/output/harmony.1735052610653.ppk .pushy/output/harmony.1735052678646.ppk .pushy/output/hdiff.ppk-patch",
"hdiffFromApp": "pushy hdiffFromApp .pushy/output/version-1.0.0.app .pushy/output/harmony.1735052610653.ppk .pushy/output/hdiff.app-patch", "hdiffFromApp": "pushy hdiffFromApp .pushy/output/version-1.0.0.app .pushy/output/harmony.1735052610653.ppk .pushy/output/hdiff.app-patch",
@@ -18,7 +18,7 @@
"@react-native-oh/react-native-harmony": "^0.72.59", "@react-native-oh/react-native-harmony": "^0.72.59",
"react": "18.2.0", "react": "18.2.0",
"react-native": "0.72.5", "react-native": "0.72.5",
"react-native-update": "latest" "react-native-update": "^10.35.4"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",
@@ -40,4 +40,4 @@
"engines": { "engines": {
"node": ">=16" "node": ">=16"
} }
} }

View File

@@ -12,7 +12,7 @@
"react-native-paper": "^5.14.5", "react-native-paper": "^5.14.5",
"react-native-safe-area-context": "^5.6.1", "react-native-safe-area-context": "^5.6.1",
"react-native-svg": "^15.13.0", "react-native-svg": "^15.13.0",
"react-native-update": "^10.34.4", "react-native-update": "^10.35.6",
"react-native-vector-icons": "^10.3.0", "react-native-vector-icons": "^10.3.0",
}, },
"devDependencies": { "devDependencies": {
@@ -1430,7 +1430,7 @@
"react-native-svg": ["react-native-svg@15.13.0", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-/YPK+PAAXg4T0x2d2vYPvqqAhOYid2bRKxUVT7STIyd1p2JxWmsGQkfZxXCkEFN7TwLfIyVlT5RimT91Pj/qXw=="], "react-native-svg": ["react-native-svg@15.13.0", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-/YPK+PAAXg4T0x2d2vYPvqqAhOYid2bRKxUVT7STIyd1p2JxWmsGQkfZxXCkEFN7TwLfIyVlT5RimT91Pj/qXw=="],
"react-native-update": ["react-native-update@10.34.4", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-yuXlff7EMUDyp1js2NylOw9jT0sVXoc5rpaRhzoYYcwfQTQq1Qp53qpyupDuUj43MEv5ikfJ6xBd/iRpXuanNg=="], "react-native-update": ["react-native-update@10.35.6", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-2k16I1QdI4wVbepaXjf+Ej9vSpnL7hpzTknitK0s4dI+hVah+cKVntnIexW4DdIpyTk7abCLVJH4MUFGjlaUSQ=="],
"react-native-url-polyfill": ["react-native-url-polyfill@2.0.0", "", { "dependencies": { "whatwg-url-without-unicode": "8.0.0-3" }, "peerDependencies": { "react-native": "*" } }, "sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA=="], "react-native-url-polyfill": ["react-native-url-polyfill@2.0.0", "", { "dependencies": { "whatwg-url-without-unicode": "8.0.0-3" }, "peerDependencies": { "react-native": "*" } }, "sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA=="],

View File

@@ -1835,7 +1835,7 @@ PODS:
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- SocketRocket - SocketRocket
- Yoga - Yoga
- react-native-update (10.34.4): - react-native-update (10.35.6):
- boost - boost
- DoubleConversion - DoubleConversion
- fast_float - fast_float
@@ -1854,7 +1854,7 @@ PODS:
- React-graphics - React-graphics
- React-ImageManager - React-ImageManager
- React-jsi - React-jsi
- react-native-update/RCTPushy (= 10.34.4) - react-native-update/RCTPushy (= 10.35.6)
- React-NativeModulesApple - React-NativeModulesApple
- React-RCTFabric - React-RCTFabric
- React-renderercss - React-renderercss
@@ -1866,7 +1866,7 @@ PODS:
- SocketRocket - SocketRocket
- SSZipArchive - SSZipArchive
- Yoga - Yoga
- react-native-update/RCTPushy (10.34.4): - react-native-update/RCTPushy (10.35.6):
- boost - boost
- DoubleConversion - DoubleConversion
- fast_float - fast_float
@@ -2800,7 +2800,7 @@ SPEC CHECKSUMS:
React-Mapbuffer: 9d2434a42701d6144ca18f0ca1c4507808ca7696 React-Mapbuffer: 9d2434a42701d6144ca18f0ca1c4507808ca7696
React-microtasksnativemodule: 75b6604b667d297292345302cc5bfb6b6aeccc1b React-microtasksnativemodule: 75b6604b667d297292345302cc5bfb6b6aeccc1b
react-native-safe-area-context: c6e2edd1c1da07bdce287fa9d9e60c5f7b514616 react-native-safe-area-context: c6e2edd1c1da07bdce287fa9d9e60c5f7b514616
react-native-update: 822780a6d3c8482d47ba50b5801ed295c0dfcaff react-native-update: 5e2274c66e654b001fae360600f5a9314c1c67e1
React-NativeModulesApple: 879fbdc5dcff7136abceb7880fe8a2022a1bd7c3 React-NativeModulesApple: 879fbdc5dcff7136abceb7880fe8a2022a1bd7c3
React-oscompat: 93b5535ea7f7dff46aaee4f78309a70979bdde9d React-oscompat: 93b5535ea7f7dff46aaee4f78309a70979bdde9d
React-perflogger: 5536d2df3d18fe0920263466f7b46a56351c0510 React-perflogger: 5536d2df3d18fe0920263466f7b46a56351c0510

View File

@@ -21,7 +21,7 @@
"react-native-paper": "^5.14.5", "react-native-paper": "^5.14.5",
"react-native-safe-area-context": "^5.6.1", "react-native-safe-area-context": "^5.6.1",
"react-native-svg": "^15.13.0", "react-native-svg": "^15.13.0",
"react-native-update": "^10.34.4", "react-native-update": "^10.35.6",
"react-native-vector-icons": "^10.3.0" "react-native-vector-icons": "^10.3.0"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -19,6 +19,33 @@
7. meta 信息及开放 API提供更高扩展性。 7. meta 信息及开放 API提供更高扩展性。
8. 提供付费的专人技术支持。 8. 提供付费的专人技术支持。
### 与其他热更新库对比
| 对比维度 | react-native-update | expo-update | react-native-code-push |
|---------|---------------------|-------------|------------------------|
| **价格/成本** | 提供免费额度,多级梯度付费(最低约 66 元/月),流量不单独计费 | 提供免费额度,多级梯度付费(最低约 136 元/月),超出流量额外计费 | ❌ **已停运**Microsoft App Center 已于 2025 年 3 月 31 日停止服务) |
| **更新包大小** | ⭐⭐⭐⭐⭐ 几十 KB增量更新 | ⭐⭐⭐ 全量更新(通常几十 MB | ❌ **已停运** |
| **中国地区访问速度** | ⭐⭐⭐⭐⭐ 阿里云 CDN速度极快 | ⭐⭐ 国外服务器,可能较慢 | ❌ **已停运** |
| **iOS 支持** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **Android 支持** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **鸿蒙支持** | ✅ 支持 | ❌ 不支持 | ❌ **已停运** |
| **Expo 支持** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **RN 版本支持** | ⭐⭐⭐⭐⭐ 第一时间支持最新版本 | ⭐⭐⭐⭐ 跟随 Expo SDK | ❌ **已停运** |
| **新架构支持** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **Hermes 支持** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **崩溃回滚** | ✅ 自动回滚机制 | ✅ 支持 | ❌ **已停运** |
| **管理界面** | ✅ 命令行工具 + Web 管理界面 | ✅ Expo Dashboard | ❌ **已停运** |
| **CI/CD 集成** | ✅ 支持 | ✅ 支持 | ❌ **已停运** |
| **API 扩展性** | ✅ Meta 信息 + 开放 API | ⚠️ 有限 | ❌ **已停运** |
| **中文文档/支持** | ⭐⭐⭐⭐⭐ 完整中文文档,中文社区支持 | ⭐⭐ 英文为主 | ❌ **已停运** |
| **技术支持** | ✅ 付费专人技术支持 | ⚠️ 社区支持 | ❌ **已停运** |
| **服务器部署** | ✅ 可托管也可付费私有部署 | ✅ Expo 托管EAS Update | ❌ **已停运** |
| **更新策略** | 灵活配置(静默/提示/立即/延迟) | 相对固定 | ❌ **已停运** |
| **流量消耗** | ⭐⭐⭐⭐⭐ 极低(增量更新) | ⭐⭐⭐ 较高(全量更新) | ❌ **已停运** |
| **更新成功率** | ⭐⭐⭐⭐⭐ 极高(国内 CDN 优势) | ⭐⭐⭐ 中等 | ❌ **已停运** |
### 本地开发 ### 本地开发
``` ```

View File

@@ -22,6 +22,10 @@ public class UpdateContext {
public static boolean DEBUG = false; public static boolean DEBUG = false;
private static ReactInstanceManager mReactInstanceManager; private static ReactInstanceManager mReactInstanceManager;
private static boolean isUsingBundleUrl = false; private static boolean isUsingBundleUrl = false;
// Singleton instance
private static UpdateContext sInstance;
private static final Object sLock = new Object();
public UpdateContext(Context context) { public UpdateContext(Context context) {
this.context = context; this.context = context;
@@ -54,13 +58,17 @@ public class UpdateContext {
boolean buildTimeChanged = !buildTime.equals(storedBuildTime); boolean buildTimeChanged = !buildTime.equals(storedBuildTime);
if (packageVersionChanged || buildTimeChanged) { if (packageVersionChanged || buildTimeChanged) {
// Execute cleanUp before clearing SharedPreferences to avoid race condition
this.cleanUp();
SharedPreferences.Editor editor = sp.edit(); SharedPreferences.Editor editor = sp.edit();
editor.clear(); editor.clear();
editor.putString("packageVersion", packageVersion); editor.putString("packageVersion", packageVersion);
editor.putString("buildTime", buildTime); editor.putString("buildTime", buildTime);
editor.apply(); // Use commit() instead of apply() to ensure synchronous write completion
// This prevents race condition where getBundleUrl() might read null values
this.cleanUp(); // if called before apply() completes
editor.commit();
} }
} }
@@ -227,12 +235,26 @@ public class UpdateContext {
return mReactInstanceManager; return mReactInstanceManager;
} }
/**
* Get singleton instance of UpdateContext
*/
public static UpdateContext getInstance(Context context) {
if (sInstance == null) {
synchronized (sLock) {
if (sInstance == null) {
sInstance = new UpdateContext(context.getApplicationContext());
}
}
}
return sInstance;
}
public static String getBundleUrl(Context context) { public static String getBundleUrl(Context context) {
return new UpdateContext(context.getApplicationContext()).getBundleUrl(); return getInstance(context).getBundleUrl();
} }
public static String getBundleUrl(Context context, String defaultAssetsUrl) { public static String getBundleUrl(Context context, String defaultAssetsUrl) {
return new UpdateContext(context.getApplicationContext()).getBundleUrl(defaultAssetsUrl); return getInstance(context).getBundleUrl(defaultAssetsUrl);
} }
public String getBundleUrl() { public String getBundleUrl() {
@@ -273,6 +295,7 @@ public class UpdateContext {
if (lastVersion == null) { if (lastVersion == null) {
editor.remove("currentVersion"); editor.remove("currentVersion");
} else { } else {
editor.remove("lastVersion");
editor.putString("currentVersion", lastVersion); editor.putString("currentVersion", lastVersion);
} }
editor.putBoolean("firstTimeOk", true); editor.putBoolean("firstTimeOk", true);

View File

@@ -27,7 +27,7 @@ public class UpdateModule extends NativePushySpec {
} }
public UpdateModule(ReactApplicationContext reactContext) { public UpdateModule(ReactApplicationContext reactContext) {
this(reactContext, new UpdateContext(reactContext.getApplicationContext())); this(reactContext, UpdateContext.getInstance(reactContext));
} }
@Override @Override

View File

@@ -40,7 +40,7 @@ public class UpdateModule extends ReactContextBaseJavaModule {
} }
public UpdateModule(ReactApplicationContext reactContext) { public UpdateModule(ReactApplicationContext reactContext) {
this(reactContext, new UpdateContext(reactContext.getApplicationContext())); this(reactContext, UpdateContext.getInstance(reactContext));
} }
@Override @Override

View File

@@ -0,0 +1,39 @@
import fs from 'fs';
import path from 'path';
export function reactNativeUpdatePlugin() {
return {
pluginId: 'reactNativeUpdatePlugin',
apply(node) {
node.registerTask({
name: 'reactNativeUpdatePlugin',
run: () => {
const cwd = process.cwd();
const metaFilePath = path.resolve(
cwd,
'entry/src/main/resources/rawfile/meta.json',
);
fs.mkdirSync(path.dirname(metaFilePath), { recursive: true });
const moduleJsonPath = path.resolve(cwd, 'AppScope/app.json5');
let versionName = '';
if (fs.existsSync(moduleJsonPath)) {
const content = fs.readFileSync(moduleJsonPath, 'utf-8');
const match = content.match(
/(?:"versionName"|versionName):\s*["']([^"']+)["']/,
);
versionName = match?.[1] || '';
}
const metaContent = {
pushy_build_time: new Date().toISOString(),
versionName,
};
fs.writeFileSync(metaFilePath, JSON.stringify(metaContent, null, 2));
console.log(`Build time written to ${metaFilePath}`);
},
});
},
};
}

View File

@@ -6,14 +6,14 @@
"lockfileVersion": 3, "lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": { "specifiers": {
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38" "@rnoh/react-native-openharmony@^0.72.96": "@rnoh/react-native-openharmony@0.72.96"
}, },
"packages": { "packages": {
"@rnoh/react-native-openharmony@0.72.38": { "@rnoh/react-native-openharmony@0.72.96": {
"name": "", "name": "",
"version": "0.72.38", "version": "0.72.96",
"integrity": "sha512-br5SIrbB0OarSLirenleE7eTOX1lNccMJ7nb/G7qWTyJ7kW4DalmTXVKYpoT2qaOLls1uEE7McD1OjbZZM9jug==", "integrity": "sha512-gBbm8LLyqi5UE7qHWdZYeQnjyncfEpCczKZUP/9M2U1Z7exR0Kya8PMKMwr1ta5ujy7w/hZVC2LomEV4QvBeqA==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.38.har", "resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.96.har",
"registryType": "ohpm" "registryType": "ohpm"
} }
} }

View File

@@ -1,13 +1,13 @@
{ {
"license": "MIT", license: 'MIT',
"types": "", types: '',
"devDependencies": {}, devDependencies: {},
"name": "pushy", name: 'pushy',
"description": "", description: '',
"main": "index.ets", main: 'index.ets',
"version": "3.1.0-0.0.7", version: '10.35.1',
"dependencies": { dependencies: {
"@rnoh/react-native-openharmony":"^0.72.38" '@rnoh/react-native-openharmony': '^0.72.96',
}, },
"modelVersion": "5.0.0" modelVersion: '5.0.0',
} }

View File

@@ -1,10 +1,7 @@
import http from '@ohos.net.http'; import http from '@ohos.net.http';
import fileIo from '@ohos.file.fs'; import fileIo from '@ohos.file.fs';
import util from '@ohos.util';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import { BusinessError } from '@kit.BasicServicesKit'; import { zlib } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
import zip from '@ohos.zlib';
import { EventHub } from './EventHub'; import { EventHub } from './EventHub';
import { DownloadTaskParams } from './DownloadTaskParams'; import { DownloadTaskParams } from './DownloadTaskParams';
import Pushy from 'librnupdate.so'; import Pushy from 'librnupdate.so';
@@ -37,7 +34,9 @@ export class DownloadTask {
if (stat.isDirectory()) { if (stat.isDirectory()) {
const files = await fileIo.listFile(path); const files = await fileIo.listFile(path);
for (const file of files) { for (const file of files) {
if (file === '.' || file === '..') continue; if (file === '.' || file === '..') {
continue;
}
await this.removeDirectory(`${path}/${file}`); await this.removeDirectory(`${path}/${file}`);
} }
await fileIo.rmdir(path); await fileIo.rmdir(path);
@@ -57,7 +56,7 @@ export class DownloadTask {
try { try {
try { try {
const exists = fileIo.accessSync(params.targetFile); let exists = fileIo.accessSync(params.targetFile);
if (exists) { if (exists) {
await fileIo.unlink(params.targetFile); await fileIo.unlink(params.targetFile);
} else { } else {
@@ -65,7 +64,7 @@ export class DownloadTask {
0, 0,
params.targetFile.lastIndexOf('/'), params.targetFile.lastIndexOf('/'),
); );
const exists = fileIo.accessSync(targetDir); exists = fileIo.accessSync(targetDir);
if (!exists) { if (!exists) {
await fileIo.mkdir(targetDir); await fileIo.mkdir(targetDir);
} }
@@ -128,64 +127,12 @@ export class DownloadTask {
}); });
} }
private async copyFile(from: string, to: string): Promise<void> {
let reader;
let writer;
try {
reader = fileIo.openSync(from, fileIo.OpenMode.READ_ONLY);
writer = fileIo.openSync(
to,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
const arrayBuffer = new ArrayBuffer(4096);
let bytesRead: number;
do {
bytesRead = await fileIo
.read(reader.fd, arrayBuffer)
.catch((err: BusinessError) => {
throw Error(
`Error reading file: ${err.message}, code: ${err.code}`,
);
});
if (bytesRead > 0) {
const buf = buffer.from(arrayBuffer, 0, bytesRead);
await fileIo
.write(writer.fd, buf.buffer, {
offset: 0,
length: bytesRead,
})
.catch((err: BusinessError) => {
throw Error(
`Error writing file: ${err.message}, code: ${err.code}`,
);
});
}
} while (bytesRead > 0);
console.info('File copied successfully');
} catch (error) {
console.error('Copy file failed:', error);
throw error;
} finally {
if (reader !== undefined) {
fileIo.closeSync(reader);
}
if (writer !== undefined) {
fileIo.closeSync(writer);
}
}
}
private async doFullPatch(params: DownloadTaskParams): Promise<void> { private async doFullPatch(params: DownloadTaskParams): Promise<void> {
await this.downloadFile(params); await this.downloadFile(params);
await this.removeDirectory(params.unzipDirectory); await this.removeDirectory(params.unzipDirectory);
await fileIo.mkdir(params.unzipDirectory); await fileIo.mkdir(params.unzipDirectory);
try { await zlib.decompressFile(params.targetFile, params.unzipDirectory);
await zip.decompressFile(params.targetFile, params.unzipDirectory);
} catch (error) {
console.error('Unzip failed:', error);
throw error;
}
} }
private async processUnzippedFiles(directory: string): Promise<ZipFile> { private async processUnzippedFiles(directory: string): Promise<ZipFile> {
@@ -193,7 +140,9 @@ export class DownloadTask {
try { try {
const files = await fileIo.listFile(directory); const files = await fileIo.listFile(directory);
for (const file of files) { for (const file of files) {
if (file === '.' || file === '..') continue; if (file === '.' || file === '..') {
continue;
}
const filePath = `${directory}/${file}`; const filePath = `${directory}/${file}`;
const stat = await fileIo.stat(filePath); const stat = await fileIo.stat(filePath);
@@ -230,7 +179,7 @@ export class DownloadTask {
let foundDiff = false; let foundDiff = false;
let foundBundlePatch = false; let foundBundlePatch = false;
const copyList: Map<string, Array<any>> = new Map(); const copyList: Map<string, Array<any>> = new Map();
await zip.decompressFile(params.targetFile, params.unzipDirectory); await zlib.decompressFile(params.targetFile, params.unzipDirectory);
const zipFile = await this.processUnzippedFiles(params.unzipDirectory); const zipFile = await this.processUnzippedFiles(params.unzipDirectory);
for (const entry of zipFile.entries) { for (const entry of zipFile.entries) {
const fn = entry.filename; const fn = entry.filename;
@@ -246,7 +195,7 @@ export class DownloadTask {
const copies = obj.copies; const copies = obj.copies;
for (const to in copies) { for (const to in copies) {
let from = copies[to]; let from = copies[to].replace('resources/rawfile/', '');
if (from === '') { if (from === '') {
from = to; from = to;
} }
@@ -295,10 +244,6 @@ export class DownloadTask {
throw error; throw error;
} }
} }
if (fn !== '.DS_Store') {
await zip.decompressFile(fn, params.unzipDirectory);
}
} }
if (!foundDiff) { if (!foundDiff) {
@@ -317,14 +262,20 @@ export class DownloadTask {
let foundDiff = false; let foundDiff = false;
let foundBundlePatch = false; let foundBundlePatch = false;
const copyList: Map<string, Array<any>> = new Map(); await zlib.decompressFile(params.targetFile, params.unzipDirectory);
await zip.decompressFile(params.targetFile, params.unzipDirectory);
const zipFile = await this.processUnzippedFiles(params.unzipDirectory); const zipFile = await this.processUnzippedFiles(params.unzipDirectory);
for (const entry of zipFile.entries) { for (const entry of zipFile.entries) {
const fn = entry.filename; const fn = entry.filename;
if (fn === '__diff.json') { if (fn === '__diff.json') {
foundDiff = true; foundDiff = true;
await fileIo
.copyDir(params.originDirectory + '/', params.unzipDirectory + '/')
.catch(error => {
console.error('copy error:', error);
});
let jsonContent = ''; let jsonContent = '';
const bufferArray = new Uint8Array(entry.content); const bufferArray = new Uint8Array(entry.content);
for (let i = 0; i < bufferArray.length; i++) { for (let i = 0; i < bufferArray.length; i++) {
@@ -332,22 +283,23 @@ export class DownloadTask {
} }
const obj = JSON.parse(jsonContent); const obj = JSON.parse(jsonContent);
const copies = obj.copies; const { copies, deletes } = obj;
for (const to in copies) { for (const [to, from] of Object.entries(copies)) {
let from = copies[to]; await fileIo
if (from === '') { .copyFile(
from = to; `${params.originDirectory}/${from}`,
} `${params.unzipDirectory}/${to}`,
)
if (!copyList.has(from)) { .catch(error => {
copyList.set(from, []); console.error('copy error:', error);
} });
}
const target = copyList.get(from); for (const fileToDelete of Object.keys(deletes)) {
if (target) { await fileIo
const toFile = `${params.unzipDirectory}/${to}`; .unlink(`${params.unzipDirectory}/${fileToDelete}`)
target.push(toFile); .catch(error => {
} console.error('delete error:', error);
});
} }
continue; continue;
} }
@@ -389,8 +341,6 @@ export class DownloadTask {
} }
} }
} }
await zip.decompressFile(entry.filename, params.unzipDirectory);
} }
if (!foundDiff) { if (!foundDiff) {
@@ -406,27 +356,14 @@ export class DownloadTask {
copyList: Map<string, Array<string>>, copyList: Map<string, Array<string>>,
): Promise<void> { ): Promise<void> {
try { try {
const bundlePath = this.context.bundleCodeDir; const resourceManager = this.context.resourceManager;
const files = await fileIo.listFile(bundlePath); for (const [from, targets] of copyList.entries()) {
for (const file of files) { const fromContent = await resourceManager.getRawFileContent(from);
if (file === '.' || file === '..') continue; for (const target of targets) {
const fileStream = fileIo.createStreamSync(target, 'w+');
const targets = copyList.get(file); fileStream.writeSync(fromContent.buffer);
if (targets) { fileStream.close();
let lastTarget: string | undefined;
for (const target of targets) {
console.info(`Copying from resource ${file} to ${target}`);
if (lastTarget) {
await this.copyFile(lastTarget, target);
} else {
const sourcePath = `${bundlePath}/${file}`;
await this.copyFile(sourcePath, target);
lastTarget = target;
}
}
} }
} }
} catch (error) { } catch (error) {
@@ -443,7 +380,9 @@ export class DownloadTask {
try { try {
const files = await fileIo.listFile(params.unzipDirectory); const files = await fileIo.listFile(params.unzipDirectory);
for (const file of files) { for (const file of files) {
if (file.startsWith('.')) continue; if (file.startsWith('.')) {
continue;
}
const filePath = `${params.unzipDirectory}/${file}`; const filePath = `${params.unzipDirectory}/${file}`;
const stat = await fileIo.stat(filePath); const stat = await fileIo.stat(filePath);

View File

@@ -1,49 +1,44 @@
import { HotReloadConfig, JSBundleProvider, JSBundleProviderError, JSPackagerClientConfig } from '@rnoh/react-native-openharmony'; import {
import fileIo from '@ohos.file.fs'; FileJSBundle,
HotReloadConfig,
JSBundleProvider,
JSBundleProviderError
} from '@rnoh/react-native-openharmony';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';
import { UpdateContext } from './UpdateContext'; import { UpdateContext } from './UpdateContext';
export class PushyFileJSBundleProvider extends JSBundleProvider { export class PushyFileJSBundleProvider extends JSBundleProvider {
private updateContext: UpdateContext; private updateContext: UpdateContext;
private filePath: string = '' private path: string = ''
constructor(context: common.UIAbilityContext) { constructor(context: common.UIAbilityContext) {
super(); super();
this.updateContext = new UpdateContext(context); this.updateContext = new UpdateContext(context);
} this.path = this.updateContext.getBundleUrl();
getURL(): string {
return this.updateContext.getBundleUrl()?.substring(1);
} }
async getBundle(): Promise<ArrayBuffer> { getURL(): string {
return this.path;
}
async getBundle(): Promise<FileJSBundle> {
if (!this.path) {
throw new JSBundleProviderError({
whatHappened: 'No pushy bundle found. using default bundle',
howCanItBeFixed: ['']
})
}
try { try {
this.filePath = this.updateContext.getBundleUrl(); await fs.access(this.path, fs.OpenMode.READ_ONLY);
const res = fileIo.accessSync(this.filePath); return {
if (res) { filePath: this.path
const file = fileIo.openSync(this.filePath, fileIo.OpenMode.READ_ONLY);
try {
const stat = await fileIo.stat(this.filePath);
const fileSize = stat.size;
const buffer = new ArrayBuffer(fileSize);
const bytesRead = fileIo.readSync(file.fd, buffer, {
offset: 0,
length: fileSize
});
if (bytesRead !== fileSize) {
throw new Error(`Failed to read entire file: read ${bytesRead} of ${fileSize} bytes`);
}
return buffer;
} finally {
fileIo.closeSync(file.fd);
}
} }
throw new Error('Update bundle not found');
} catch (error) { } catch (error) {
throw new JSBundleProviderError({ throw new JSBundleProviderError({
whatHappened: `Couldn't load JSBundle from ${this.filePath}`, whatHappened: `Couldn't load JSBundle from ${this.path}`,
extraData: error, extraData: error,
howCanItBeFixed: [`Check if a bundle exists at "${this.filePath}" on your device.`] howCanItBeFixed: [`Check if a bundle exists at "${this.path}" on your device.`]
}) })
} }
} }

View File

@@ -1,9 +1,10 @@
import { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts'; import {
TurboModule,
TurboModuleContext,
} from '@rnoh/react-native-openharmony/ts';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences'; import dataPreferences from '@ohos.data.preferences';
import { bundleManager } from '@kit.AbilityKit'; import { bundleManager } from '@kit.AbilityKit';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';
import logger from './Logger'; import logger from './Logger';
import { UpdateModuleImpl } from './UpdateModuleImpl'; import { UpdateModuleImpl } from './UpdateModuleImpl';
import { UpdateContext } from './UpdateContext'; import { UpdateContext } from './UpdateContext';
@@ -23,50 +24,60 @@ export class PushyTurboModule extends TurboModule {
EventHub.getInstance().setRNInstance(ctx.rnInstance); EventHub.getInstance().setRNInstance(ctx.rnInstance);
} }
getConstants(): Object {
logger.debug(TAG, ',call getConstants');
const context = this.mUiCtx;
const preferencesManager = dataPreferences.getPreferencesSync(context, {
name: 'update',
});
const isFirstTime = preferencesManager.getSync(
'isFirstTime',
false,
) as boolean;
const rolledBackVersion = preferencesManager.getSync(
'rolledBackVersion',
'',
) as string;
const uuid = preferencesManager.getSync('uuid', '') as string;
const currentVersion = preferencesManager.getSync(
'currentVersion',
'',
) as string;
const currentVersionInfo = this.context.getKv(`hash_${currentVersion}`);
const buildTime = preferencesManager.getSync('buildTime', '') as string;
const isUsingBundleUrl = this.context.getIsUsingBundleUrl();
let bundleFlags =
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
let packageVersion = '';
try {
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
packageVersion = bundleInfo?.versionName || 'Unknown';
} catch (error) {
console.error('Failed to get bundle info:', error);
}
getConstants(): Object { if (isFirstTime) {
logger.debug(TAG, ',call getConstants'); preferencesManager.deleteSync('isFirstTime');
const context = this.mUiCtx; }
const preferencesManager = dataPreferences.getPreferencesSync(context,{ name: 'update' });
const isFirstTime = preferencesManager.getSync('isFirstTime', false) as boolean; if (rolledBackVersion) {
const rolledBackVersion = preferencesManager.getSync('rolledBackVersion', '') as string; preferencesManager.deleteSync('rolledBackVersion');
const uuid = preferencesManager.getSync('uuid', '') as string; }
const currentVersion = preferencesManager.getSync('currentVersion', '') as string;
const currentVersionInfo = this.context.getKv(`hash_${currentVersion}`); return {
const buildTime = preferencesManager.getSync('buildTime', '') as string; downloadRootDir: `${context.filesDir}/_update`,
const isUsingBundleUrl = this.context.getIsUsingBundleUrl(); currentVersionInfo,
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; packageVersion,
let packageVersion = ''; currentVersion,
try { buildTime,
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags); isUsingBundleUrl,
packageVersion = bundleInfo?.versionName || 'Unknown'; isFirstTime,
} catch (error) { rolledBackVersion,
console.error('Failed to get bundle info:', error); uuid,
};
} }
if (isFirstTime) { setLocalHashInfo(hash: string, info: string): boolean {
preferencesManager.deleteSync('isFirstTime');
}
if (rolledBackVersion) {
preferencesManager.deleteSync('rolledBackVersion');
}
return {
downloadRootDir: `${context.filesDir}/_update`,
currentVersionInfo,
packageVersion,
currentVersion,
buildTime,
isUsingBundleUrl,
isFirstTime,
rolledBackVersion,
uuid,
};
}
setLocalHashInfo(hash: string, info: string): boolean {
logger.debug(TAG, ',call setLocalHashInfo'); logger.debug(TAG, ',call setLocalHashInfo');
return UpdateModuleImpl.setLocalHashInfo(this.context, hash, info); return UpdateModuleImpl.setLocalHashInfo(this.context, hash, info);
} }
@@ -75,9 +86,9 @@ getConstants(): Object {
return UpdateModuleImpl.getLocalHashInfo(this.context, hash); return UpdateModuleImpl.getLocalHashInfo(this.context, hash);
} }
async setUuid(uuid: string): Promise<boolean> { async setUuid(uuid: string): Promise<boolean> {
logger.debug(TAG, ',call setUuid'); logger.debug(TAG, ',call setUuid');
return UpdateModuleImpl.setUuid(this.context,uuid); return UpdateModuleImpl.setUuid(this.context, uuid);
} }
async reloadUpdate(options: { hash: string }): Promise<void> { async reloadUpdate(options: { hash: string }): Promise<void> {
@@ -95,31 +106,45 @@ getConstants(): Object {
return UpdateModuleImpl.markSuccess(this.context); return UpdateModuleImpl.markSuccess(this.context);
} }
async downloadPatchFromPpk(options: { updateUrl: string; hash: string; originHash: string }): Promise<void> { async downloadPatchFromPpk(options: {
updateUrl: string;
hash: string;
originHash: string;
}): Promise<void> {
logger.debug(TAG, ',call downloadPatchFromPpk'); logger.debug(TAG, ',call downloadPatchFromPpk');
return UpdateModuleImpl.downloadPatchFromPpk(this.context, options); return UpdateModuleImpl.downloadPatchFromPpk(this.context, options);
} }
async downloadPatchFromPackage(options: { updateUrl: string; hash: string }): Promise<void> { async downloadPatchFromPackage(options: {
updateUrl: string;
hash: string;
}): Promise<void> {
logger.debug(TAG, ',call downloadPatchFromPackage'); logger.debug(TAG, ',call downloadPatchFromPackage');
return UpdateModuleImpl.downloadPatchFromPackage(this.context, options); return UpdateModuleImpl.downloadPatchFromPackage(this.context, options);
} }
async downloadFullUpdate(options: { updateUrl: string; hash: string }): Promise<void> { async downloadFullUpdate(options: {
updateUrl: string;
hash: string;
}): Promise<void> {
logger.debug(TAG, ',call downloadFullUpdate'); logger.debug(TAG, ',call downloadFullUpdate');
return UpdateModuleImpl.downloadFullUpdate(this.context, options); return UpdateModuleImpl.downloadFullUpdate(this.context, options);
} }
async downloadAndInstallApk(options: { url: string; target: string; hash: string }): Promise<void> { async downloadAndInstallApk(options: {
url: string;
target: string;
hash: string;
}): Promise<void> {
logger.debug(TAG, ',call downloadAndInstallApk'); logger.debug(TAG, ',call downloadAndInstallApk');
return UpdateModuleImpl.downloadAndInstallApk(this.mUiCtx, options); return UpdateModuleImpl.downloadAndInstallApk(this.mUiCtx, options);
} }
addListener(eventName: string): void { addListener(_eventName: string): void {
logger.debug(TAG, ',call addListener'); logger.debug(TAG, ',call addListener');
} }
removeListeners(count: number): void { removeListeners(_count: number): void {
logger.debug(TAG, ',call removeListeners'); logger.debug(TAG, ',call removeListeners');
} }
} }

View File

@@ -37,10 +37,10 @@ export class UpdateContext {
this.preferences.putSync('packageVersion', packageVersion); this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush(); this.preferences.flush();
} else if (storedVersion && packageVersion !== storedVersion) { } else if (storedVersion && packageVersion !== storedVersion) {
this.cleanUp();
this.preferences.clear(); this.preferences.clear();
this.preferences.putSync('packageVersion', packageVersion); this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush(); this.preferences.flush();
this.cleanUp();
} }
} catch (e) { } catch (e) {
console.error('Failed to init preferences:', e); console.error('Failed to init preferences:', e);
@@ -101,6 +101,7 @@ export class UpdateContext {
params.hash = hash; params.hash = hash;
params.listener = listener; params.listener = listener;
params.targetFile = `${this.rootDir}/${hash}.ppk`; params.targetFile = `${this.rootDir}/${hash}.ppk`;
params.unzipDirectory = `${this.rootDir}/${hash}`;
const downloadTask = new DownloadTask(this.context); const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params); await downloadTask.execute(params);
} catch (e) { } catch (e) {
@@ -162,8 +163,8 @@ export class UpdateContext {
const downloadTask = new DownloadTask(this.context); const downloadTask = new DownloadTask(this.context);
return await downloadTask.execute(params); return await downloadTask.execute(params);
} catch (e) { } catch (e) {
throw e;
console.error('Failed to download APK patch:', e); console.error('Failed to download APK patch:', e);
throw e;
} }
} }
@@ -188,18 +189,11 @@ export class UpdateContext {
} }
} }
public static getBundleUrl( public getBundleUrl() {
context: common.UIAbilityContext,
defaultAssetsUrl?: string,
): string {
return new UpdateContext(context).getBundleUrl(defaultAssetsUrl);
}
public getBundleUrl(defaultAssetsUrl?: string): string {
UpdateContext.isUsingBundleUrl = true; UpdateContext.isUsingBundleUrl = true;
const currentVersion = this.getCurrentVersion(); const currentVersion = this.getCurrentVersion();
if (!currentVersion) { if (!currentVersion) {
return defaultAssetsUrl; return '';
} }
if (!this.isFirstTime()) { if (!this.isFirstTime()) {
if (!this.preferences.getSync('firstTimeOk', true)) { if (!this.preferences.getSync('firstTimeOk', true)) {
@@ -221,7 +215,7 @@ export class UpdateContext {
version = this.rollBack(); version = this.rollBack();
} }
} }
return defaultAssetsUrl; return '';
} }
getPackageVersion(): string { getPackageVersion(): string {
@@ -251,6 +245,7 @@ export class UpdateContext {
if (!lastVersion) { if (!lastVersion) {
this.preferences.deleteSync('currentVersion'); this.preferences.deleteSync('currentVersion');
} else { } else {
this.preferences.deleteSync('lastVersion');
this.preferences.putSync('currentVersion', lastVersion); this.preferences.putSync('currentVersion', lastVersion);
} }
this.preferences.putSync('firstTimeOk', true); this.preferences.putSync('firstTimeOk', true);

View File

@@ -78,7 +78,7 @@ RCT_EXPORT_MODULE(RCTPushy);
NSString *storedBuildTime = [defaults stringForKey:paramBuildTime]; NSString *storedBuildTime = [defaults stringForKey:paramBuildTime];
// If stored versions don't exist, write current versions first // If stored versions don't exist, write current versions first
if (!storedPackageVersion || !storedBuildTime) { if (!storedPackageVersion && !storedBuildTime) {
[defaults setObject:curPackageVersion forKey:paramPackageVersion]; [defaults setObject:curPackageVersion forKey:paramPackageVersion];
[defaults setObject:curBuildTime forKey:paramBuildTime]; [defaults setObject:curBuildTime forKey:paramBuildTime];
storedPackageVersion = curPackageVersion; storedPackageVersion = curPackageVersion;
@@ -86,7 +86,7 @@ RCT_EXPORT_MODULE(RCTPushy);
} }
BOOL packageVersionChanged = ![curPackageVersion isEqualToString:storedPackageVersion]; BOOL packageVersionChanged = ![curPackageVersion isEqualToString:storedPackageVersion];
BOOL buildTimeChanged = ![curBuildTime isEqualToString:storedBuildTime]; BOOL buildTimeChanged = curBuildTime && ![curBuildTime isEqualToString:storedBuildTime];
if (packageVersionChanged || buildTimeChanged) { if (packageVersionChanged || buildTimeChanged) {
// Clear all update data and store new versions // Clear all update data and store new versions
@@ -304,8 +304,8 @@ RCT_EXPORT_METHOD(setNeedUpdate:(NSDictionary *)options
if (hash.length) { if (hash.length) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *lastVersion = nil; NSString *lastVersion = nil;
if ([defaults objectForKey:keyPushyInfo]) { NSDictionary *pushyInfo = [defaults objectForKey:keyPushyInfo];
NSDictionary *pushyInfo = [defaults objectForKey:keyPushyInfo]; if (pushyInfo) {
lastVersion = pushyInfo[paramCurrentVersion]; lastVersion = pushyInfo[paramCurrentVersion];
} }
@@ -679,4 +679,4 @@ RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
} }
#endif #endif
@end @end

View File

@@ -1,6 +1,6 @@
{ {
"name": "react-native-update", "name": "react-native-update",
"version": "10.34.9", "version": "10.35.8",
"description": "react-native hot update", "description": "react-native hot update",
"main": "src/index", "main": "src/index",
"scripts": { "scripts": {

View File

@@ -1,6 +1,7 @@
import { createContext, useContext } from 'react'; import { createContext, useContext } from 'react';
import { CheckResult, ProgressData } from './type'; import { CheckResult, ProgressData } from './type';
import { Pushy, Cresc } from './client'; import { Pushy, Cresc } from './client';
import i18n from './i18n';
const noop = () => {}; const noop = () => {};
const asyncNoop = () => Promise.resolve(); const asyncNoop = () => Promise.resolve();
@@ -50,7 +51,16 @@ export const UpdateContext = createContext<{
lastError?: Error; lastError?: Error;
}>(defaultContext); }>(defaultContext);
export const useUpdate = () => useContext(UpdateContext); export const useUpdate = __DEV__ ? () => {
const context = useContext(UpdateContext);
// 检查是否在 UpdateProvider 内部使用
if (!context.client) {
throw new Error(i18n.t('error_use_update_outside_provider'));
}
return context;
} : () => useContext(UpdateContext);
/** @deprecated Please use `useUpdate` instead */ /** @deprecated Please use `useUpdate` instead */
export const usePushy = useUpdate; export const usePushy = useUpdate;

View File

@@ -47,7 +47,7 @@ export const currentVersionInfo = _currentVersionInfo;
export const isFirstTime: boolean = PushyConstants.isFirstTime; export const isFirstTime: boolean = PushyConstants.isFirstTime;
export const rolledBackVersion: string = PushyConstants.rolledBackVersion; export const rolledBackVersion: string = PushyConstants.rolledBackVersion;
export const isRolledBack: boolean = typeof rolledBackVersion === 'string'; export const isRolledBack: boolean = !!rolledBackVersion;
export const buildTime: string = PushyConstants.buildTime; export const buildTime: string = PushyConstants.buildTime;
let uuid = PushyConstants.uuid; let uuid = PushyConstants.uuid;

View File

@@ -71,4 +71,8 @@ export default {
// Development environment messages // Development environment messages
dev_incremental_update_disabled: dev_incremental_update_disabled:
'Currently in development environment, incremental hot update cannot be executed and restart will not take effect. If you need to test effective full hot update in development environment (but will reconnect to metro after restart), please enable "ignore timestamp" switch and retry.', 'Currently in development environment, incremental hot update cannot be executed and restart will not take effect. If you need to test effective full hot update in development environment (but will reconnect to metro after restart), please enable "ignore timestamp" switch and retry.',
// Context error messages
error_use_update_outside_provider:
'useUpdate must be used within an UpdateProvider. Please wrap your component tree with <UpdateProvider client={...}>.',
}; };

View File

@@ -68,4 +68,8 @@ export default {
// Development environment messages // Development environment messages
dev_incremental_update_disabled: dev_incremental_update_disabled:
'当前是开发环境,无法执行增量式热更新,重启不会生效。如果需要在开发环境中测试可生效的全量热更新(但也会在再次重启后重新连接 metro请打开"忽略时间戳"开关再重试。', '当前是开发环境,无法执行增量式热更新,重启不会生效。如果需要在开发环境中测试可生效的全量热更新(但也会在再次重启后重新连接 metro请打开"忽略时间戳"开关再重试。',
// Context error messages
error_use_update_outside_provider:
'useUpdate 必须在 UpdateProvider 内部使用。请使用 <UpdateProvider client={...}> 包裹您的组件树。',
}; };

View File

@@ -13,7 +13,12 @@ import {
Linking, Linking,
} from 'react-native'; } from 'react-native';
import { Pushy, Cresc, sharedState } from './client'; import { Pushy, Cresc, sharedState } from './client';
import { currentVersion, packageVersion, getCurrentVersionInfo, currentVersionInfo } from './core'; import {
currentVersion,
packageVersion,
getCurrentVersionInfo,
currentVersionInfo,
} from './core';
import { import {
CheckResult, CheckResult,
ProgressData, ProgressData,
@@ -165,7 +170,7 @@ export const UpdateProvider = ({
lastChecking.current = now; lastChecking.current = now;
let rootInfo: CheckResult | undefined; let rootInfo: CheckResult | undefined;
try { try {
rootInfo = await client.checkUpdate(extra); rootInfo = { ...(await client.checkUpdate(extra)) };
} catch (e: any) { } catch (e: any) {
setLastError(e); setLastError(e);
alertError(client.t('error_update_check_failed'), e.message); alertError(client.t('error_update_check_failed'), e.message);
@@ -175,7 +180,9 @@ export const UpdateProvider = ({
if (!rootInfo) { if (!rootInfo) {
return; return;
} }
const versions = [rootInfo.expVersion, rootInfo].filter(Boolean) as VersionInfo[]; const versions = [rootInfo.expVersion, rootInfo].filter(
Boolean,
) as VersionInfo[];
delete rootInfo.expVersion; delete rootInfo.expVersion;
for (const versionInfo of versions) { for (const versionInfo of versions) {
const info: CheckResult = { const info: CheckResult = {