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

Compare commits

..

1 Commits

Author SHA1 Message Date
sunnylqm
dbca54a7f0 v10.20.0-beta.0 2025-01-11 19:23:31 +08:00
55 changed files with 1191 additions and 1435 deletions

View File

@@ -1,16 +1,25 @@
## 运行harmony_use_pushy项目步骤
### 1. 先在react-native-update根目录执行下面命令同步C++模块
### 1.将项目克隆到本地后在项目根目录创建libs文件夹
### 2.然后将[`rnoh`](https://github.com/bozaigao/rnoh)克隆到libs文件夹中。
说明rnoh项目基于react-native 0.72.5版本适配如果使用最新的RN版本可能会报错项目适配RN新版本请关注[`gitee仓库`](https://gitee.com/openharmony-sig/ohos_react_native/tree/0.72.5-ohos-5.0-release/tester/harmony/react_native_openharmony/src/main)
### 3.进入rnoh项目执行下面命令对rnoh项目依赖的C++库进行初始化;
```
yarn submodule
git submodule update --init --recursive
```
### 2. 在项目根目录执行下面命令安装第三方依赖
### 4. 确保在react-native-update根目录已经执行过yarn submodule命令
说明这个命令会在harmony/src/main/cpp目录生成HDiffPatch和lzma的C++模块依赖。
### 5. 在项目根目录执行下面命令安装第三方依赖。
```
yarn install
```
### 3. 在项目根目录执行下面命令生成bundle包文件。
### 6. 在项目根目录执行下面命令生成bundle包文件。
```
yarn build
```
@@ -18,8 +27,8 @@ yarn build
**注意⚠️**在使用pushy bundle --platform harmony命令进行打包的默认bundle包名是Hbundle.harmony.js不要随意修改包名因为diff是匹配该包名进行生成的。
### 4. 使用DevEco Studio IDE打开harmony目录然后执行sync运行项目
### 7. 使用DevEco Studio IDE打开harmony目录然后执行sync运行项目
![image](./sync.png)
### 5 运行效果图
![image](./demo.png)
### 8 运行效果图
![image](./demo.png)

View File

@@ -37,6 +37,10 @@
}
]
},
{
name: 'rnoh',
srcPath: '../libs/rnoh',
},
{
name: 'pushy',
srcPath: '../node_modules/react-native-update/harmony',

View File

@@ -14,11 +14,11 @@ export function generatePushyBuildTime(str?: string) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const moduleJsonPath = path.resolve(__dirname, '../AppScope/app.json5');
const moduleJsonPath = path.resolve(__dirname, './oh-package.json5');
let versionName = '';
if (fs.existsSync(moduleJsonPath)) {
const moduleContent = fs.readFileSync(moduleJsonPath, 'utf-8');
const versionMatch = moduleContent.match(/"versionName":\s*"([^"]+)"/);
const versionMatch = moduleContent.match(/"version":\s*"([^"]+)"/);
if (versionMatch && versionMatch[1]) {
versionName = versionMatch[1];
}
@@ -41,4 +41,4 @@ export function generatePushyBuildTime(str?: string) {
export default {
system: hapTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[generatePushyBuildTime()] /* Custom plugin to extend the functionality of Hvigor. */
}
}

View File

@@ -5,25 +5,24 @@
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": {
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38",
"pushy@../../node_modules/react-native-update/harmony": "pushy@../../node_modules/react-native-update/harmony"
"pushy@../../node_modules/react-native-update/harmony": "pushy@../../node_modules/react-native-update/harmony",
"rnoh@../../libs/rnoh": "rnoh@../../libs/rnoh"
},
"packages": {
"@rnoh/react-native-openharmony@0.72.38": {
"name": "@rnoh/react-native-openharmony",
"version": "0.72.38",
"integrity": "sha512-br5SIrbB0OarSLirenleE7eTOX1lNccMJ7nb/G7qWTyJ7kW4DalmTXVKYpoT2qaOLls1uEE7McD1OjbZZM9jug==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.38.har",
"registryType": "ohpm"
},
"pushy@../../node_modules/react-native-update/harmony": {
"name": "pushy",
"version": "3.1.0-0.0.7",
"resolved": "../../node_modules/react-native-update/harmony",
"registryType": "local",
"dependencies": {
"@rnoh/react-native-openharmony": "^0.72.38"
"rnoh": "file:../../../libs/rnoh"
}
},
"rnoh@../../libs/rnoh": {
"name": "rnoh",
"version": "0.72.12",
"resolved": "../../libs/rnoh",
"registryType": "local"
}
}
}

View File

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

View File

@@ -2,23 +2,12 @@ cmake_minimum_required(VERSION 3.16)
project(rnapp)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(NODE_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../node_modules")
set(OH_MODULE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules/@rnoh/react-native-openharmony/src/main/cpp")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../libs/rnoh/src/main/cpp")
set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(LOG_VERBOSITY_LEVEL 1)
set(CMAKE_ASM_FLAGS "-Wno-error=unused-command-line-argument -Qunused-arguments")
set(CMAKE_CXX_FLAGS "-fstack-protector-strong -Wl,-z,relro,-z,now,-z,noexecstack -s -fPIE -pie")
set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(WITH_HITRACE_SYSTRACE 1) # for other CMakeLists.txt files to use
add_compile_definitions(WITH_HITRACE_SYSTRACE)
add_subdirectory("${OH_MODULES}/pushy/src/main/cpp" ./pushy)
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
file(GLOB GENERATED_CPP_FILES "${CMAKE_CURRENT_SOURCE_DIR}/generated/*.cpp") # this line is needed by codegen v1
add_library(rnoh_app SHARED
${GENERATED_CPP_FILES}
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)

View File

@@ -1,4 +1,4 @@
import type {RNPackageContext, RNPackage} from '@rnoh/react-native-openharmony/ts';
import type {RNPackageContext, RNPackage} from 'rnoh/ts';
import {PushyPackage} from 'pushy/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {

View File

@@ -1,4 +1,4 @@
import {RNAbility} from '@rnoh/react-native-openharmony';
import {RNAbility} from 'rnoh/ts';
export default class EntryAbility extends RNAbility {
getPagePath() {

View File

@@ -1,32 +1,26 @@
import { FileJSBundleProvider } from 'pushy/src/main/ets/FileJSBundleProvider';
import { ComponentBuilderContext, RNOHCoreContext,RNAbility } from '@rnoh/react-native-openharmony';
import { ComponentBuilderContext, JSBundleProvider, RNOHLogger } from 'rnoh';
import {
RNApp,
RNAbility,
AnyJSBundleProvider,
ResourceJSBundleProvider,
TraceJSBundleProviderDecorator,
} from '@rnoh/react-native-openharmony'
} from 'rnoh'
import { createRNPackages } from '../RNPackagesFactory'
import preferences from '@ohos.data.preferences';
const arkTsComponentNames: Array<string> = [];
@Builder
export function buildCustomRNComponent(ctx: ComponentBuilderContext) {
// There seems to be a problem with the placement of ArkTS components in mixed mode. Nested Stack temporarily avoided.
Stack() {
}
.position({ x: 0, y: 0 })
export function CustomComponentBuilder(ctx: ComponentBuilderContext) {
}
const wrappedCustomRNComponentBuilder = wrapBuilder(buildCustomRNComponent)
@Entry
@Component
struct Index {
@StorageLink('RNOHCoreContext') private rnohCoreContext: RNOHCoreContext | undefined = undefined
@StorageLink('RNAbility') private rnAbility: RNAbility | undefined = undefined
@State shouldShow: boolean = false
@State message: string = 'Hello World';
aboutToAppear(): void {
this.shouldShow = true
@@ -36,37 +30,28 @@ struct Index {
// NOTE: this is required since `Ability`'s `onBackPressed` function always
// terminates or puts the app in the background, but we want Ark to ignore it completely
// when handled by RN
this.rnohCoreContext!.dispatchBackPress()
// this.preferences = preferences.getPreferencesSync(this.context, {name:'update'});
return true
return this.rnAbility?.onBackPress();
}
build() {
Column() {
if (this.rnohCoreContext && this.shouldShow) {
if (this.rnAbility && this.shouldShow) {
RNApp({
rnInstanceConfig: {
createRNPackages,
enableNDKTextMeasuring: true,
enableBackgroundExecutor: false,
enableCAPIArchitecture: true,
arkTsComponentNames: arkTsComponentNames,
},
rnInstanceConfig: { createRNPackages },
initialProps: { "foo": "bar" } as Record<string, string>,
appKey: "harmony_use_pushy",
wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
buildCustomComponent: CustomComponentBuilder,
onSetUp: (rnInstance) => {
rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP")
},
jsBundleProvider: new TraceJSBundleProviderDecorator(
new AnyJSBundleProvider([
// MetroJSBundleProvider.fromServerIp('127.0.0.1'),
// new ResourceJSBundleProvider(rnohCoreContext.uiAbilityContext.resourceManager, 'hermes_bundle.hbc'),
new FileJSBundleProvider(this.rnohCoreContext.uiAbilityContext),
new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle.harmony.js')
// new ResourceJSBundleProvider(this.rnAbility.context.resourceManager, 'hermes_bundle.hbc'),
new FileJSBundleProvider(this.rnAbility.context),
new ResourceJSBundleProvider(this.rnAbility.context.resourceManager, 'bundle.harmony.js')
]),
this.rnohCoreContext.logger),
this.rnAbility.getLogger()),
})
}
}

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +0,0 @@
{
"pushy_build_time": "2025-03-09T01:57:42.464Z",
"versionName": "1.0.0"
}

View File

@@ -1,14 +0,0 @@
{
"ios": {
"appId": 24794,
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
},
"android": {
"appId": 27509,
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
},
"harmony": {
"appId": 29140,
"appKey": "JLklGflGIRbY-cMebjQwm1J1"
}
}

View File

@@ -13,8 +13,5 @@
"suppressImplicitAnyIndexErrors": true,
"strict": false
}
},
"overrides": {
"@rnoh/react-native-openharmony": "0.72.38"
}
}

View File

@@ -8,7 +8,7 @@
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
},
"harmony": {
"appId": 29140,
"appKey": "JLklGflGIRbY-cMebjQwm1J1"
"appId": 29040,
"appKey": "gdzeAqAFE5Jew15c5Df8EKU9"
}
}

View File

@@ -5520,9 +5520,9 @@ mustache@^4.2.0:
integrity sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==
nanoid@^3.3.3:
version "3.3.9"
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.9.tgz#e0097d8e026b3343ff053e9ccd407360a03f503a"
integrity sha512-SppoicMGpZvbF1l3z4x7No3OlIjP7QJvC9XR7AhZr1kL133KHnKPztkKDc+Ir4aJ/1VhTySrtKhrsycmrMQfvg==
version "3.3.8"
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.8.tgz#b1be3030bee36aaff18bacb375e5cce521684baf"
integrity sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==
natural-compare-lite@^1.4.0:
version "1.4.0"
@@ -6003,7 +6003,7 @@ react-is@^17.0.1:
integrity sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==
"react-native-update@file:../..":
version "10.26.1"
version "10.15.1"
dependencies:
nanoid "^3.3.3"
react-native-url-polyfill "^2.0.0"

View File

@@ -30,7 +30,6 @@ build/
local.properties
*.iml
*.hprof
.kotlin/
# node.js
#

View File

@@ -68,7 +68,7 @@ def enableProguardInReleaseBuilds = false
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
def jscFlavor = 'org.webkit:android-jsc:+'
android {
ndkVersion rootProject.ext.ndkVersion

View File

@@ -3,9 +3,9 @@ buildscript {
buildToolsVersion = "35.0.0"
minSdkVersion = 24
compileSdkVersion = 35
targetSdkVersion = 35
ndkVersion = "27.1.12297006"
kotlinVersion = "2.0.21"
targetSdkVersion = 34
ndkVersion = "26.1.10909125"
kotlinVersion = "1.9.24"
}
repositories {
google()

View File

@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View File

@@ -86,7 +86,8 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@ const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
* Metro configuration
* https://reactnative.dev/docs/metro
*
* @type {import('@react-native/metro-config').MetroConfig}
* @type {import('metro-config').MetroConfig}
*/
const config = {};

View File

@@ -14,15 +14,15 @@
"dev:harmony": "react-native bundle-harmony --dev"
},
"dependencies": {
"form-data": "^4.0.2",
"form-data": "^4.0.1",
"patch-package": "^8.0.0",
"react": "19.0.0",
"react-native": "0.78.0",
"react-native-camera-kit": "^14.2.0",
"postinstall-postinstall": "^2.1.0",
"react": "18.3.1",
"react-native": "0.76.6",
"react-native-camera-kit": "^14.1.0",
"react-native-paper": "^5.13.1",
"react-native-safe-area-context": "^5.3.0",
"react-native-svg": "^15.11.2",
"react-native-update": "^10.26.4",
"react-native-safe-area-context": "^5.1.0",
"react-native-update": "^10.19.6",
"react-native-vector-icons": "^10.2.0"
},
"devDependencies": {
@@ -32,24 +32,26 @@
"@react-native-community/cli": "15.0.1",
"@react-native-community/cli-platform-android": "15.0.1",
"@react-native-community/cli-platform-ios": "15.0.1",
"@react-native/babel-preset": "0.78.0",
"@react-native/eslint-config": "0.78.0",
"@react-native/metro-config": "0.78.0",
"@react-native/typescript-config": "0.78.0",
"@types/react": "^19.0.0",
"@types/react-test-renderer": "^19.0.0",
"@react-native/babel-preset": "0.76.6",
"@react-native/eslint-config": "0.76.6",
"@react-native/metro-config": "0.76.6",
"@react-native/typescript-config": "0.76.6",
"@types/react": "^18.2.6",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^29.6.3",
"detox": "^20.32.0",
"eslint": "^8.19.0",
"jest": "^29.6.3",
"prettier": "2.8.8",
"react-test-renderer": "19.0.0",
"typescript": "5.8.2"
"react-test-renderer": "18.3.1",
"typescript": "5.7.3"
},
"engines": {
"node": ">=18"
},
"trustedDependencies": [
"detox",
"dtrace-provider"
"dtrace-provider",
"postinstall-postinstall"
]
}

View File

@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-11.5 -10.23174 23 20.46348">
<title>React Logo</title>
<circle cx="0" cy="0" r="2.05" fill="#61dafb"/>
<g stroke="#61dafb" stroke-width="1" fill="none">
<ellipse rx="11" ry="4.2"/>
<ellipse rx="11" ry="4.2" transform="rotate(60)"/>
<ellipse rx="11" ry="4.2" transform="rotate(120)"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 365 B

View File

@@ -20,12 +20,11 @@ import {
Portal,
} from 'react-native-paper';
import {Camera} from 'react-native-camera-kit';
import {LocalSvg} from 'react-native-svg/css';
import TestConsole from './TestConsole';
import _updateConfig from '../update.json';
import {UpdateProvider, Pushy, Cresc, useUpdate} from 'react-native-update';
import {PushyProvider, Pushy, usePushy} from 'react-native-update';
const {appKey} = _updateConfig[Platform.OS];
function App() {
@@ -40,7 +39,7 @@ function App() {
currentHash,
parseTestQrCode,
progress: {received, total} = {},
} = useUpdate();
} = usePushy();
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
const [showTestConsole, setShowTestConsole] = useState(false);
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
@@ -92,21 +91,11 @@ function App() {
/>
</Modal>
</Portal>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 10}}>
<Text>png:</Text>
<Image
resizeMode={'contain'}
source={require('./assets/shezhi.png')}
style={styles.image}
/>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 10}}>
<Text>svg:</Text>
<LocalSvg
asset={require('./assets/react-logo.svg')}
style={{width: 30, height: 30}}
/>
</View>
<Image
resizeMode={'contain'}
source={require('./assets/shezhi.png')}
style={styles.image}
/>
<Text style={styles.instructions}>
{'\n'}
: {packageVersion}
@@ -203,24 +192,17 @@ const styles = StyleSheet.create({
image: {},
});
// use Pushy for China users
// const updateClient = new Pushy({
// appKey,
// debug: true,
// });
// use Cresc for global users
const updateClient = new Cresc({
const pushyClient = new Pushy({
appKey,
debug: true,
});
export default function Root() {
return (
<UpdateProvider client={updateClient}>
<PushyProvider client={pushyClient}>
<PaperProvider>
<App />
</PaperProvider>
</UpdateProvider>
</PushyProvider>
);
}

View File

@@ -2,8 +2,6 @@
本组件是面向 React Native 提供热更新功能的组件,详情请访问我们的官方网站 <https://pushy.reactnative.cn>
**现已支持鸿蒙以及新架构**
### 快速开始
请查看[文档](https://pushy.reactnative.cn/docs/getting-started.html)
@@ -22,7 +20,7 @@
### 本地开发
```
$ git clone git@github.com:reactnativecn/react-native-update.git
$ git clone git@github.com:reactnativecn/react-native-pushy.git
$ cd react-native-pushy/Example/testHotUpdate
$ yarn
$ yarn start
@@ -34,4 +32,4 @@ $ yarn start
本组件由[React Native 中文网](https://reactnative.cn/)独家发布,如有定制需求可以[联系我们](https://reactnative.cn/about.html#content)。
关于此插件发现任何问题,可以前往[Issues](https://github.com/reactnativecn/react-native-update/issues)发帖提问。
关于此插件发现任何问题,可以前往[Issues](https://github.com/reactnativecn/react-native-pushy/issues)发帖提问。

View File

@@ -49,7 +49,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
private void removeDirectory(File file) throws IOException {
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Removing " + file);
Log.d("RNUpdate", "Removing " + file);
}
if (file.isDirectory()) {
File[] files = file.listFiles();
@@ -88,7 +88,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
BufferedSink sink = Okio.buffer(Okio.sink(writePath));
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Downloading " + url);
Log.d("RNUpdate", "Downloading " + url);
}
long bytesRead = 0;
@@ -98,7 +98,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
received += bytesRead;
sink.emit();
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Progress " + received + "/" + contentLength);
Log.d("RNUpdate", "Progress " + received + "/" + contentLength);
}
int percentage = (int)(received * 100.0 / contentLength + 0.5);
@@ -115,7 +115,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
sink.close();
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Download finished");
Log.d("RNUpdate", "Download finished");
}
}
@@ -244,7 +244,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Unzip finished");
Log.d("RNUpdate", "Unzip finished");
}
}
@@ -260,7 +260,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
File lastTarget = null;
for (File target: targets) {
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Copying from resource " + fn + " to " + target);
Log.d("RNUpdate", "Copying from resource " + fn + " to " + target);
}
if (lastTarget != null) {
copyFile(lastTarget, target);
@@ -352,7 +352,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
copyFromResource(copyList);
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Unzip finished");
Log.d("RNUpdate", "Unzip finished");
}
}
@@ -418,12 +418,12 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
throw new Error("bundle patch not found");
}
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Unzip finished");
Log.d("RNUpdate", "Unzip finished");
}
}
private void doCleanUp(DownloadTaskParams param) throws IOException {
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Start cleaning up");
Log.d("RNUpdate", "Start cleaning up");
}
File root = param.unzipDirectory;
for (File sub : root.listFiles()) {
@@ -499,7 +499,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
default:
break;
}
Log.e("react-native-update", "download task failed", e);
Log.e("pushy", "download task failed", e);
if (params[0].listener != null) {
params[0].listener.onDownloadFailed(e);

View File

@@ -98,20 +98,23 @@ public class UpdateModuleImpl {
}
});
}catch (Exception e){
promise.reject("downloadPatchFromPpk failed: "+e.getMessage());
promise.reject("执行报错:" + e.getMessage());
}
}
public static void reloadUpdate(UpdateContext updateContext, ReactApplicationContext mContext, ReadableMap options, Promise promise) {
final String hash = options.getString("hash");
if (hash == null || hash.isEmpty()) {
promise.reject("hash不能为空");
return;
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.switchVersion(hash);
final Context application = mContext.getApplicationContext();
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
try {
updateContext.switchVersion(hash);
final Context application = mContext.getApplicationContext();
ReactInstanceManager instanceManager = updateContext.getCustomReactInstanceManager();
if (instanceManager == null) {
@@ -119,10 +122,12 @@ public class UpdateModuleImpl {
}
try {
JSBundleLoader loader = JSBundleLoader.createFileLoader(UpdateContext.getBundleUrl(application));
Field loadField = instanceManager.getClass().getDeclaredField("mBundleLoader");
loadField.setAccessible(true);
loadField.set(instanceManager, loader);
} catch (Throwable err) {
promise.reject("pushy:"+err.getMessage());
Field jsBundleField = instanceManager.getClass().getDeclaredField("mJSBundleFile");
jsBundleField.setAccessible(true);
jsBundleField.set(instanceManager, UpdateContext.getBundleUrl(application));
@@ -132,36 +137,15 @@ public class UpdateModuleImpl {
promise.resolve(true);
} catch (Throwable err) {
promise.reject(err);
Log.e("pushy", "switchVersion failed ", err);
final Activity currentActivity = mContext.getCurrentActivity();
if (currentActivity == null) {
return;
}
try {
java.lang.reflect.Method getReactDelegateMethod =
ReactActivity.class.getMethod("getReactDelegate");
ReactDelegate reactDelegate = (ReactDelegate)
getReactDelegateMethod.invoke(currentActivity);
Field reactHostField = ReactDelegate.class.getDeclaredField("mReactHost");
reactHostField.setAccessible(true);
Object reactHost = reactHostField.get(reactDelegate);
// Access the mReactHostDelegate field
Field reactHostDelegateField = reactHost.getClass().getDeclaredField("mReactHostDelegate");
reactHostDelegateField.setAccessible(true);
Object reactHostDelegate = reactHostDelegateField.get(reactHost);
// Modify the jsBundleLoader field
Field jsBundleLoaderField = reactHostDelegate.getClass().getDeclaredField("jsBundleLoader");
jsBundleLoaderField.setAccessible(true);
jsBundleLoaderField.set(reactHostDelegate, loader);
// Get the reload method with a String parameter
java.lang.reflect.Method reloadMethod = reactHost.getClass().getMethod("reload", String.class);
// Invoke the reload method with a reason
reloadMethod.invoke(reactHost, "react-native-update");
final ReactDelegate reactDelegate = ((ReactActivity) currentActivity).getReactDelegate();
reactDelegate.reload();
} catch (Throwable e) {
currentActivity.runOnUiThread(new Runnable() {
@Override
@@ -171,54 +155,72 @@ public class UpdateModuleImpl {
});
}
}
promise.resolve(true);
}
});
}
public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options, Promise promise) {
final String hash = options.getString("hash");
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
updateContext.switchVersion(hash);
promise.resolve(true);
} catch (Throwable err) {
promise.reject("switchVersionLater failed: "+err.getMessage());
Log.e("pushy", "switchVersionLater failed", err);
public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options,Promise promise) {
try {
final String hash = options.getString("hash");
if(hash==null || hash.isEmpty()){
promise.reject("hash不能为空");
return;
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
updateContext.switchVersion(hash);
promise.resolve(true);
} catch (Throwable err) {
promise.reject("switchVersionLater failed:"+err.getMessage());
Log.e("pushy", "switchVersionLater failed", err);
}
}
}
});
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
}
public static void markSuccess(UpdateContext updateContext, Promise promise) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.markSuccess();
promise.resolve(true);
}
});
public static void markSuccess(UpdateContext updateContext,Promise promise) {
try {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.markSuccess();
promise.resolve(true);
}
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
}
public static void setUuid(UpdateContext updateContext, String uuid, Promise promise) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setKv("uuid", uuid);
promise.resolve(true);
}
});
try {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
updateContext.setKv("uuid", uuid);
promise.resolve(true);
}
});
} catch (Exception e){
promise.reject("执行报错:"+e.getMessage());
}
}
public static boolean check(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
mapper.readValue(json, Map.class);
System.out.println("String can be converted to Map");
return true;
} catch (IOException e) {
System.out.println("String cannot be converted to Map");
return false;
}
}
@@ -228,12 +230,12 @@ public class UpdateModuleImpl {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (check(info)) {
if(!check(info)){
updateContext.setKv("hash_" + hash, info);
promise.reject("校验报错:json字符串格式错误");
}else {
updateContext.setKv("hash_" + hash, info);
promise.resolve(true);
} else {
updateContext.setKv("hash_" + hash, info);
promise.reject("setLocalHashInfo failed: invalid json string");
}
}
});
@@ -244,7 +246,7 @@ public class UpdateModuleImpl {
if (check(value)) {
promise.resolve(value);
} else {
promise.reject("getLocalHashInfo failed: invalid json string");
promise.reject("校验报错:json字符串格式错误");
}
}

View File

@@ -1 +0,0 @@
["https://cresc-server-pthxtmvcnf.ap-southeast-1.fcapp.run"]

11
harmony/README.OpenSource Normal file
View File

@@ -0,0 +1,11 @@
[
{
"Name": "react-native-netinfo",
"License": "MIT License",
"License File": "https://github.com/react-native-netinfo/react-native-netinfo/blob/master/LICENSE",
"Version Number": "11.1.0",
"Owner" : "Matt Oakes <hello@mattoakes.net>"
"Upstream URL": "https://github.com/react-native-netinfo/react-native-netinfo",
"Description": "React Native Network Info API for Android, iOS, macOS, Windows & Web. It allows you to get information on:Connection typeConnection quality"
}
]

View File

@@ -5,15 +5,14 @@
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": {
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38"
"rnoh@../../../libs/rnoh": "rnoh@../../../libs/rnoh"
},
"packages": {
"@rnoh/react-native-openharmony@0.72.38": {
"name": "@rnoh/react-native-openharmony",
"version": "0.72.38",
"integrity": "sha512-br5SIrbB0OarSLirenleE7eTOX1lNccMJ7nb/G7qWTyJ7kW4DalmTXVKYpoT2qaOLls1uEE7McD1OjbZZM9jug==",
"resolved": "https://ohpm.openharmony.cn/ohpm/@rnoh/react-native-openharmony/-/react-native-openharmony-0.72.38.har",
"registryType": "ohpm"
"rnoh@../../../libs/rnoh": {
"name": "rnoh",
"version": "0.72.12",
"resolved": "../../../libs/rnoh",
"registryType": "local"
}
}
}

View File

@@ -7,6 +7,6 @@
"main": "index.ets",
"version": "3.1.0-0.0.7",
"dependencies": {
"@rnoh/react-native-openharmony":"^0.72.38"
"rnoh": "file:../../../libs/rnoh"
}
}

View File

@@ -1 +0,0 @@
../../../../../harmony/oh_modules/.ohpm/@rnoh+react-native-openharmony@0.72.38/oh_modules/@rnoh/react-native-openharmony

View File

@@ -72,18 +72,16 @@ napi_value HdiffPatch(napi_env env, napi_callback_info info) {
// 创建结果buffer
napi_value resultBuffer;
uint8_t* outPtr;
void* data;
status = napi_create_arraybuffer(env, newsize, &data, &resultBuffer);
status = napi_create_buffer(env, newsize, (void**)&outPtr, &resultBuffer);
if (status != napi_ok) {
napi_throw_error(env, NULL, "Failed to create result buffer");
return NULL;
}
outPtr = (uint8_t*)data;
// 执行patch
_check(kHPatch_ok==hpatch_by_mem(originPtr, originLength, outPtr, newsize,
patchPtr, patchLength, &patInfo), "hpatch");
return resultBuffer;
_clear:

View File

@@ -65,13 +65,9 @@ export class DownloadTask {
0,
params.targetFile.lastIndexOf('/'),
);
const exists = fileIo.accessSync(targetDir);
if(!exists){
await fileIo.mkdir(targetDir);
}
await fileIo.mkdir(targetDir);
}
} catch (error) {
throw error;
}
const response = await httpRequest.request(params.url, {
@@ -82,11 +78,12 @@ export class DownloadTask {
'Content-Type': 'application/octet-stream',
},
});
if (response.responseCode > 299) {
throw new Error(`Server error: ${response.responseCode}`);
}
const contentLength = parseInt(response.header['content-length'] || '0');
const contentLength = parseInt(response.header['Content-Length'] || '0');
const writer = await fileIo.open(
params.targetFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.READ_WRITE,
@@ -105,12 +102,8 @@ export class DownloadTask {
this.onProgressUpdate(received, contentLength);
}
await fileIo.close(writer);
const stats = await fileIo.stat(params.targetFile);
const fileSize = stats.size;
if (fileSize !== contentLength) {
throw new Error(`Download incomplete: expected ${contentLength} bytes but got ${stats.size} bytes`);
}
const stat = await fileIo.stat(params.targetFile);
const fileSize = stat.size;
} catch (error) {
console.error('Download failed:', error);
throw error;
@@ -120,7 +113,7 @@ export class DownloadTask {
}
private onProgressUpdate(received: number, total: number): void {
this.eventHub.emit('RCTPushyDownloadProgress', {
this.eventHub.emit('downloadProgress', {
received,
total,
hash: this.hash,
@@ -295,9 +288,7 @@ export class DownloadTask {
}
}
if(fn !== '.DS_Store'){
await zip.decompressFile(fn, params.unzipDirectory);
}
await zip.decompressFile(entry.filename, params.unzipDirectory);
}
if (!foundDiff) {

View File

@@ -3,7 +3,6 @@ type EventCallback = (data: any) => void;
export class EventHub {
private static instance: EventHub;
private listeners: Map<string, Set<EventCallback>>;
private rnInstance: any;
private constructor() {
this.listeners = new Map();
@@ -28,12 +27,12 @@ export class EventHub {
}
public emit(event: string, data: any): void {
if (this.rnInstance) {
this.rnInstance.emitDeviceEvent(event, data);
}
}
setRNInstance(instance: any) {
this.rnInstance = instance;
this.listeners.get(event)?.forEach(callback => {
try {
callback(data);
} catch (error) {
console.error(`Error in event listener for ${event}:`, error);
}
});
}
}

View File

@@ -1,4 +1,4 @@
import { HotReloadConfig, JSBundleProvider, JSBundleProviderError, JSPackagerClientConfig } from '@rnoh/react-native-openharmony';
import { HotReloadConfig, JSBundleProvider, JSBundleProviderError, JSPackagerClientConfig } from 'rnoh';
import fileIo from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import { UpdateContext } from './UpdateContext';
@@ -40,15 +40,20 @@ export class FileJSBundleProvider extends JSBundleProvider {
}
throw new Error('Update bundle not found');
} catch (error) {
throw new JSBundleProviderError({
whatHappened: `Couldn't load JSBundle from ${this.filePath}`,
extraData: error,
howCanItBeFixed: [`Check if a bundle exists at "${this.filePath}" on your device.`]
})
throw new JSBundleProviderError(`Couldn't load JSBundle from ${this.filePath}`, error)
}
}
getAppKeys(): string[] {
return [];
}
getHotReloadConfig(): HotReloadConfig | null {
return null;
}
getJSPackagerClientConfig(): JSPackagerClientConfig | null {
return null;
}
}

View File

@@ -1,5 +1,5 @@
import { RNPackage, TurboModulesFactory } from '@rnoh/react-native-openharmony/ts';
import type { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
import { RNPackage, TurboModulesFactory } from 'rnoh/ts';
import type { TurboModule, TurboModuleContext } from 'rnoh/ts';
import { PushyTurboModule } from './PushyTurboModule';
class PushyTurboModulesFactory extends TurboModulesFactory {

View File

@@ -1,4 +1,4 @@
import { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
import { TurboModule, TurboModuleContext } from 'rnoh/ts';
import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences';
import { bundleManager } from '@kit.AbilityKit';
@@ -7,7 +7,6 @@ import { BusinessError } from '@ohos.base';
import logger from './Logger';
import { UpdateModuleImpl } from './UpdateModuleImpl';
import { UpdateContext } from './UpdateContext';
import { EventHub } from './EventHub';
const TAG = "PushyTurboModule"
@@ -19,8 +18,9 @@ export class PushyTurboModule extends TurboModule {
super(ctx);
logger.debug(TAG, ",PushyTurboModule constructor");
this.mUiCtx = ctx.uiAbilityContext
let rnInstance = ctx.rnInstance
this.context = new UpdateContext(this.mUiCtx)
EventHub.getInstance().setRNInstance(ctx.rnInstance)
// rnInstance.emitDeviceEvent("Pushy",{code: err.code, message: err.message});
}

View File

@@ -26,18 +26,15 @@ export class UpdateContext {
this.initPreferences();
}
private initPreferences() {
private async initPreferences() {
try {
this.preferences = preferences.getPreferencesSync(this.context, {name:'update'});
const packageVersion = this.getPackageVersion();
const storedVersion = this.preferences.getSync('packageVersion', '');
if(!storedVersion){
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
} else if (storedVersion && packageVersion !== storedVersion) {
this.preferences.clear();
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
this.preferences = await preferences.getPreferences(this.context, 'update');
const packageVersion = await this.getPackageVersion();
const storedVersion = await this.preferences.get('packageVersion', '');
if (packageVersion !== storedVersion) {
await this.preferences.clear();
await this.preferences.put('packageVersion', packageVersion);
await this.preferences.flush();
this.cleanUp();
}
} catch (e) {
@@ -45,33 +42,33 @@ export class UpdateContext {
}
}
public setKv(key: string, value: string): void {
this.preferences.putSync(key, value);
this.preferences.flush();
public async setKv(key: string, value: string): Promise<void> {
await this.preferences.put(key, value);
await this.preferences.flush();
}
public getKv(key: string): string {
return this.preferences.getSync(key, '') as string;
public async getKv(key: string): Promise<string> {
return await this.preferences.get(key, '') as string;
}
public isFirstTime(): boolean {
return this.preferences.getSync('firstTime', false) as boolean;
public async isFirstTime(): Promise<boolean> {
return await this.preferences.get('firstTime', false) as boolean;
}
public rolledBackVersion(): string {
return this.preferences.getSync('rolledBackVersion', '') as string;
public async rolledBackVersion(): Promise<string> {
return await this.preferences.get('rolledBackVersion', '') as string;
}
public markSuccess(): void {
this.preferences.putSync('firstTimeOk', true);
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
const curVersion = this.preferences.getSync('currentVersion', '') as string;
public async markSuccess(): Promise<void> {
await this.preferences.put('firstTimeOk', true);
const lastVersion = await this.preferences.get('lastVersion', '') as string;
const curVersion = await this.preferences.get('currentVersion', '') as string;
if (lastVersion && lastVersion !== curVersion) {
this.preferences.deleteSync('lastVersion');
this.preferences.deleteSync(`hash_${lastVersion}`);
await this.preferences.delete('lastVersion');
await this.preferences.delete(`hash_${lastVersion}`);
}
this.preferences.flush();
await this.preferences.flush();
this.cleanUp();
}
@@ -140,29 +137,29 @@ export class UpdateContext {
params.unzipDirectory = `${this.rootDir}/${hash}`;
const downloadTask = new DownloadTask(this.context);
return await downloadTask.execute(params);
await downloadTask.execute(params);
} catch (e) {
throw e;
console.error('Failed to download APK patch:', e);
}
}
public switchVersion(hash: string): void {
public async switchVersion(hash: string): Promise<void> {
try {
const bundlePath = `${this.rootDir}/${hash}/bundle.harmony.js`;
if (!fileIo.accessSync(bundlePath)) {
throw new Error(`Bundle version ${hash} not found.`);
}
const lastVersion = this.getKv('currentVersion');
this.setKv('currentVersion', hash);
const lastVersion = await this.getKv('currentVersion');
await this.setKv('currentVersion', hash);
if (lastVersion && lastVersion !== hash) {
this.setKv('lastVersion', lastVersion);
await this.setKv('lastVersion', lastVersion);
}
this.setKv('firstTime', 'true');
this.setKv('firstTimeOk', 'false');
this.setKv('rolledBackVersion', "");
await this.setKv('firstTime', 'true');
await this.setKv('firstTimeOk', 'false');
await this.setKv('rolledBackVersion', null);
} catch (e) {
console.error('Failed to switch version:', e);
}
@@ -179,7 +176,7 @@ export class UpdateContext {
return defaultAssetsUrl;
}
if (!this.isFirstTime()) {
if (!this.preferences.getSync('firstTimeOk', true)) {
if (!this.preferences.get('firstTimeOk', true)) {
return this.rollBack();
}
}
@@ -214,7 +211,7 @@ export class UpdateContext {
}
public getCurrentVersion() : string {
const currentVersion = this.getKv('currentVersion');
const currentVersion = this.preferences.getSync('currentVersion', '') as string;
return currentVersion;
}

View File

@@ -1,5 +1,8 @@
import { TurboModuleContext } from 'rnoh/ts';
import dataPreferences from '@ohos.data.preferences';
import bundleManager from '@ohos.bundle.bundleManager';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';
import { UpdateContext } from './UpdateContext';
import { DownloadTaskParams } from './DownloadTaskParams';
import logger from './Logger';
@@ -56,7 +59,7 @@ export class UpdateModuleImpl {
options: { updateUrl: string; hash: string }
): Promise<void> {
try {
return await updateContext.downloadPatchFromPackage(options.updateUrl, options.hash, {
await updateContext.downloadPatchFromPackage(options.updateUrl, options.hash, {
onDownloadCompleted: (params: DownloadTaskParams) => {
return Promise.resolve();
},

View File

@@ -78,7 +78,6 @@ RCT_EXPORT_MODULE(RCTPushy);
BOOL needClearPushyInfo = ![curPackageVersion isEqualToString:packageVersion];
if (needClearPushyInfo) {
[defaults setObject:nil forKey:keyPushyInfo];
[defaults setObject:nil forKey:keyHashInfo];
[defaults setObject:@(YES) forKey:KeyPackageUpdatedMarked];
// ...need clear files later

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "10.27.0",
"version": "10.20.0-beta.0",
"description": "react-native hot update",
"main": "src/index",
"scripts": {
@@ -26,7 +26,7 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/reactnativecn/react-native-update.git"
"url": "git+https://github.com/reactnativecn/react-native-pushy.git"
},
"keywords": [
"react-native",
@@ -37,13 +37,13 @@
"author": "reactnativecn",
"license": "MIT",
"bugs": {
"url": "https://github.com/reactnativecn/react-native-update/issues"
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-native": ">=0.59.0"
},
"homepage": "https://github.com/reactnativecn/react-native-update#readme",
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
"dependencies": {
"nanoid": "^3.3.3",
"react-native-url-polyfill": "^2.0.0"
@@ -74,5 +74,6 @@
"react-native": "0.73",
"ts-jest": "^29.2.5",
"typescript": "^5.6.3"
}
},
"packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72"
}

View File

@@ -4,8 +4,6 @@ new_arch_enabled = ENV['RCT_NEW_ARCH_ENABLED'] == '1'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
podspec_dir = File.dirname(__FILE__)
Pod::Spec.new do |s|
s.name = package['name']
s.version = package['version']
@@ -18,16 +16,13 @@ Pod::Spec.new do |s|
s.cocoapods_version = '>= 1.6.0'
s.platform = :ios, "8.0"
s.platforms = { :ios => "11.0" }
s.source = { :git => 'https://github.com/reactnativecn/react-native-update.git', :tag => '#{s.version}' }
s.source = { :git => 'https://github.com/reactnativecn/react-native-pushy.git', :tag => '#{s.version}' }
s.source_files = "ios/**/*.{h,m,mm,swift}"
s.libraries = 'bz2', 'z'
s.vendored_libraries = 'RCTPushy/libRCTPushy.a'
s.pod_target_xcconfig = {
'USER_HEADER_SEARCH_PATHS' => "#{podspec_dir}/ios",
"DEFINES_MODULE" => "YES"
}
s.pod_target_xcconfig = { 'USER_HEADER_SEARCH_PATHS' => '"$(SRCROOT)/../node_modules/react-native-update/ios"' }
s.resource = 'ios/pushy_build_time.txt'
s.script_phase = { :name => 'Generate build time', :script => "set -x;date +%s > \"#{podspec_dir}/ios/pushy_build_time.txt\"", :execution_position => :before_compile }
s.script_phase = { :name => 'Generate build time', :script => 'set -x;date +%s > ${PODS_ROOT}/../../node_modules/react-native-update/ios/pushy_build_time.txt', :execution_position => :before_compile }
s.dependency 'React'
s.dependency "React-Core"
@@ -45,7 +40,7 @@ Pod::Spec.new do |s|
'android/jni/HDiffPatch/file_for_patch.{h,c}',
'android/jni/lzma/C/LzmaDec.{h,c}',
'android/jni/lzma/C/Lzma2Dec.{h,c}']
ss.public_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
ss.private_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
end
if defined?(install_modules_dependencies()) != nil

View File

@@ -1,19 +1,6 @@
import { CheckResult, ClientOptions, ProgressData, EventType } from './type';
import {
assertDev,
assertWeb,
emptyObj,
joinUrls,
log,
noop,
promiseAny,
testUrls,
} from './utils';
import {
EmitterSubscription,
Platform,
DeviceEventEmitter,
} from 'react-native';
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { emptyObj, joinUrls, log, noop, promiseAny, testUrls } from './utils';
import { EmitterSubscription, Platform } from 'react-native';
import { PermissionsAndroid } from './permissions';
import {
PushyModule,
@@ -28,42 +15,31 @@ import {
isRolledBack,
} from './core';
const SERVER_PRESETS = {
// cn
Pushy: {
main: 'https://update.react-native.cn/api',
backups: ['https://update.reactnative.cn/api'],
queryUrls: [
'https://gitee.com/sunnylqm/react-native-pushy/raw/master/endpoints.json',
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-update@master/endpoints.json',
],
},
// i18n
Cresc: {
main: 'https://api.cresc.dev',
backups: ['https://api.cresc.app'],
queryUrls: [
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-update@master/endpoints_cresc.json',
],
},
const defaultServer = {
main: 'https://update.react-native.cn/api',
backups: ['https://update.reactnative.cn/api'],
queryUrls: [
'https://gitee.com/sunnylqm/react-native-pushy/raw/master/endpoints.json',
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json',
],
};
assertWeb();
if (Platform.OS === 'web') {
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
}
const defaultClientOptions: ClientOptions = {
appKey: '',
autoMarkSuccess: true,
updateStrategy: __DEV__ ? 'alwaysAlert' : 'alertUpdateAndIgnoreError',
checkStrategy: 'both',
logger: noop,
debug: false,
throwError: false,
};
// for China users
export class Pushy {
options = defaultClientOptions;
clientType: 'Pushy' | 'Cresc' = 'Pushy';
options: PushyOptions = {
appKey: '',
server: defaultServer,
autoMarkSuccess: true,
updateStrategy: __DEV__ ? 'alwaysAlert' : 'alertUpdateAndIgnoreError',
checkStrategy: 'both',
logger: noop,
debug: false,
throwError: false,
};
lastChecking?: number;
lastRespJson?: Promise<any>;
@@ -74,7 +50,7 @@ export class Pushy {
static marked = false;
static applyingUpdate = false;
version = cInfo.rnu;
version = cInfo.pushy;
loggerPromise = (() => {
let resolve: (value?: unknown) => void = () => {};
const promise = new Promise(res => {
@@ -86,14 +62,12 @@ export class Pushy {
};
})();
constructor(options: ClientOptions, clientType?: 'Pushy' | 'Cresc') {
constructor(options: PushyOptions) {
if (Platform.OS === 'ios' || Platform.OS === 'android') {
if (!options.appKey) {
throw new Error('appKey is required');
}
}
this.clientType = clientType || 'Pushy';
this.options.server = SERVER_PRESETS[this.clientType];
this.setOptions(options);
if (isRolledBack) {
this.report({
@@ -105,7 +79,7 @@ export class Pushy {
}
}
setOptions = (options: Partial<ClientOptions>) => {
setOptions = (options: Partial<PushyOptions>) => {
for (const [key, value] of Object.entries(options)) {
if (value !== undefined) {
(this.options as any)[key] = value;
@@ -150,24 +124,15 @@ export class Pushy {
return `${endpoint}/checkUpdate/${this.options.appKey}`;
};
static assertHash = (hash: string) => {
if (!this.downloadedHash) {
if (!Pushy.downloadedHash) {
return;
}
if (hash !== this.downloadedHash) {
if (hash !== Pushy.downloadedHash) {
log(`use downloaded hash ${Pushy.downloadedHash} first`);
return;
}
return true;
};
assertDebug = () => {
if (__DEV__ && !this.options.debug) {
console.info(
'You are currently in the development environment and have not enabled debug mode. The hot update check will not be performed. If you need to debug hot updates in the development environment, please set debug to true in the client.',
);
return false;
}
return true;
};
markSuccess = () => {
if (Pushy.marked || __DEV__ || !isFirstTime) {
return;
@@ -177,7 +142,10 @@ export class Pushy {
this.report({ type: 'markSuccess' });
};
switchVersion = async (hash: string) => {
if (!assertDev('switchVersion()')) {
if (__DEV__) {
console.warn(
'您调用了switchVersion方法但是当前是开发环境不会进行任何操作。',
);
return;
}
if (Pushy.assertHash(hash) && !Pushy.applyingUpdate) {
@@ -188,7 +156,10 @@ export class Pushy {
};
switchVersionLater = async (hash: string) => {
if (!assertDev('switchVersionLater()')) {
if (__DEV__) {
console.warn(
'您调用了switchVersionLater方法但是当前是开发环境不会进行任何操作。',
);
return;
}
if (Pushy.assertHash(hash)) {
@@ -197,17 +168,21 @@ export class Pushy {
}
};
checkUpdate = async (extra?: Record<string, any>) => {
if (!this.assertDebug()) {
if (__DEV__ && !this.options.debug) {
console.info(
'您当前处于开发环境且未启用 debug不会进行热更检查。如需在开发环境中调试热更请在 client 中设置 debug 为 true',
);
return;
}
if (!assertWeb()) {
if (Platform.OS === 'web') {
console.warn('web 端不支持热更新检查');
return;
}
if (
this.options.beforeCheckUpdate &&
(await this.options.beforeCheckUpdate()) === false
) {
log('beforeCheckUpdate returned false, skipping check');
log('beforeCheckUpdate 返回 false, 忽略检查');
return;
}
const now = Date.now();
@@ -230,12 +205,7 @@ export class Pushy {
// @ts-ignore
delete fetchBody.buildTime;
}
const stringifyBody = JSON.stringify(fetchBody);
// harmony fetch body is not string
let body: any = fetchBody;
if (Platform.OS === 'ios' || Platform.OS === 'android') {
body = stringifyBody;
}
const body = JSON.stringify(fetchBody);
const fetchPayload = {
method: 'POST',
headers: {
@@ -248,13 +218,13 @@ export class Pushy {
try {
this.report({
type: 'checking',
message: this.options.appKey + ': ' + stringifyBody,
message: this.options.appKey + ': ' + body,
});
resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e: any) {
this.report({
type: 'errorChecking',
message: `Can not connect to update server: ${e.message}. Trying backup endpoints.`,
message: 'Can not connect to update server. Trying backup endpoints.',
});
const backupEndpoints = await this.getBackupEndpoints();
if (backupEndpoints) {
@@ -336,7 +306,7 @@ export class Pushy {
this.options.beforeDownloadUpdate &&
(await this.options.beforeDownloadUpdate(info)) === false
) {
log('beforeDownloadUpdate returned false, skipping download');
log('beforeDownloadUpdate 返回 false, 忽略下载');
return;
}
if (!info.update || !hash) {
@@ -353,33 +323,19 @@ export class Pushy {
if (Pushy.progressHandlers[hash]) {
return;
}
const patchStartTime = Date.now();
if (onDownloadProgress) {
// @ts-expect-error harmony not in existing platforms
if (Platform.OS === 'harmony') {
Pushy.progressHandlers[hash] = DeviceEventEmitter.addListener(
'RCTPushyDownloadProgress',
progressData => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
} else {
Pushy.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
'RCTPushyDownloadProgress',
progressData => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
Pushy.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
'RCTPushyDownloadProgress',
progressData => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
},
);
}
let succeeded = '';
this.report({ type: 'downloading' });
let lastError: any;
let errorMessages: string[] = [];
const diffUrl = await testUrls(joinUrls(paths, diff));
if (diffUrl) {
log('downloading diff');
@@ -391,13 +347,11 @@ export class Pushy {
});
succeeded = 'diff';
} catch (e: any) {
const errorMessage = `diff error: ${e.message}`;
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
lastError = e;
if (__DEV__) {
succeeded = 'diff';
} else {
log(errorMessage);
log(`diff error: ${e.message}, try pdiff`);
}
}
}
@@ -411,13 +365,11 @@ export class Pushy {
});
succeeded = 'pdiff';
} catch (e: any) {
const errorMessage = `pdiff error: ${e.message}`;
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
lastError = e;
if (__DEV__) {
succeeded = 'pdiff';
} else {
log(errorMessage);
log(`pdiff error: ${e.message}, try full patch`);
}
}
}
@@ -431,13 +383,11 @@ export class Pushy {
});
succeeded = 'full';
} catch (e: any) {
const errorMessage = `full patch error: ${e.message}`;
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
lastError = e;
if (__DEV__) {
succeeded = 'full';
} else {
log(errorMessage);
log(`full patch error: ${e.message}`);
}
}
}
@@ -452,25 +402,15 @@ export class Pushy {
this.report({
type: 'errorUpdate',
data: { newVersion: hash },
message: errorMessages.join(';'),
});
if (lastError) {
throw lastError;
}
return;
} else {
const duration = Date.now() - patchStartTime;
const data: Record<string, any> = {
newVersion: hash,
diff: succeeded,
duration,
};
if (errorMessages.length > 0) {
data.error = errorMessages.join(';');
}
this.report({
type: 'downloadSuccess',
data,
data: { newVersion: hash, diff: succeeded },
});
}
log(`downloaded ${succeeded} hash:`, hash);
@@ -545,10 +485,3 @@ export class Pushy {
}
};
}
// for international users
export class Cresc extends Pushy {
constructor(options: ClientOptions) {
super(options, 'Cresc');
}
}

View File

@@ -1,6 +1,6 @@
import { createContext, useContext } from 'react';
import { CheckResult, ProgressData } from './type';
import { Pushy, Cresc } from './client';
import { Pushy } from './client';
const noop = () => {};
const asyncNoop = () => Promise.resolve();
@@ -19,8 +19,8 @@ export const defaultContext = {
packageVersion: '',
};
export const UpdateContext = createContext<{
checkUpdate: () => Promise<void | CheckResult>;
export const PushyContext = createContext<{
checkUpdate: () => Promise<void>;
switchVersion: () => Promise<void>;
switchVersionLater: () => Promise<void>;
markSuccess: () => void;
@@ -35,13 +35,10 @@ export const UpdateContext = createContext<{
parseTestQrCode: (code: string) => boolean;
currentHash: string;
packageVersion: string;
client?: Pushy | Cresc;
client?: Pushy;
progress?: ProgressData;
updateInfo?: CheckResult;
lastError?: Error;
}>(defaultContext);
export const useUpdate = () => useContext(UpdateContext);
/** @deprecated Please use `useUpdate` instead */
export const usePushy = useUpdate;
export const usePushy = () => useContext(PushyContext);

View File

@@ -4,9 +4,7 @@ const {
version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
const isTurboModuleEnabled =
// https://github.com/facebook/react-native/pull/48362
(global as any).__turboModuleProxy || (global as any).RN$Bridgeless;
const isTurboModuleEnabled = (global as any).__turboModuleProxy != null;
export const PushyModule =
Platform.OS === 'web'
@@ -15,12 +13,8 @@ export const PushyModule =
? require('./NativePushy').default
: NativeModules.Pushy;
export const UpdateModule = PushyModule;
if (!PushyModule) {
throw new Error(
'Failed to load react-native-update native module, please try to recompile',
);
throw new Error('react-native-update 模块无法加载,请对照安装文档检查配置。');
}
const PushyConstants = isTurboModuleEnabled
@@ -37,6 +31,12 @@ export const isRolledBack: boolean = typeof rolledBackVersion === 'string';
export const buildTime: string = PushyConstants.buildTime;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update 模块无法加载,请对照文档检查 Bundle URL 的配置',
);
}
export function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
@@ -63,7 +63,7 @@ if (!uuid) {
log('uuid: ' + uuid);
export const cInfo = {
rnu: require('../package.json').version,
pushy: require('../package.json').version,
rn: RNVersion,
os: Platform.OS + ' ' + Platform.Version,
uuid,

View File

@@ -1,4 +1,4 @@
export { Pushy, Cresc } from './client';
export { UpdateContext, usePushy, useUpdate } from './context';
export { PushyProvider, UpdateProvider } from './provider';
export { PushyModule, UpdateModule } from './core';
export { Pushy } from './client';
export { PushyContext, usePushy } from './context';
export { PushyProvider } from './provider';
export { PushyModule } from './core';

View File

@@ -12,24 +12,22 @@ import {
Platform,
Linking,
} from 'react-native';
import { Pushy, Cresc } from './client';
import { Pushy } from './client';
import { currentVersion, packageVersion, getCurrentVersionInfo } from './core';
import { CheckResult, ProgressData, UpdateTestPayload } from './type';
import { UpdateContext } from './context';
import { CheckResult, ProgressData, PushyTestPayload } from './type';
import { PushyContext } from './context';
import { URL } from 'react-native-url-polyfill';
import { isInRollout } from './isInRollout';
import { log } from './utils';
export const UpdateProvider = ({
export const PushyProvider = ({
client,
children,
}: {
client: Pushy | Cresc;
client: Pushy;
children: ReactNode;
}) => {
client = useRef(client).current;
const { options } = client;
const stateListener = useRef<NativeEventSubscription>();
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
const updateInfoRef = useRef(updateInfo);
@@ -100,14 +98,6 @@ export const UpdateProvider = ({
return false;
}
stateListener.current && stateListener.current.remove();
if (
options.afterDownloadUpdate &&
(await options.afterDownloadUpdate(info)) === false
) {
log('afterDownloadUpdate returned false, skipping');
return false;
}
if (options.updateStrategy === 'silentAndNow') {
client.switchVersion(hash);
return true;
@@ -139,7 +129,13 @@ export const UpdateProvider = ({
return false;
}
},
[client, options, alertUpdate, alertError, throwErrorIfEnabled],
[
client,
options.updateStrategy,
alertUpdate,
alertError,
throwErrorIfEnabled,
],
);
const downloadAndInstallApk = useCallback(
@@ -183,14 +179,14 @@ export const UpdateProvider = ({
setUpdateInfo(info);
if (info.expired) {
const { downloadUrl } = info;
if (downloadUrl && Pushy.apkStatus === null) {
if (downloadUrl) {
if (options.updateStrategy === 'silentAndNow') {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl);
} else {
Linking.openURL(downloadUrl);
}
return info;
return;
}
alertUpdate('提示', '您的应用版本已更新,点击更新下载安装新版本', [
{
@@ -211,7 +207,7 @@ export const UpdateProvider = ({
options.updateStrategy === 'silentAndLater'
) {
downloadUpdate(info);
return info;
return;
}
alertUpdate(
'提示',
@@ -228,7 +224,6 @@ export const UpdateProvider = ({
],
);
}
return info;
},
[
client,
@@ -244,14 +239,15 @@ export const UpdateProvider = ({
const markSuccess = client.markSuccess;
useEffect(() => {
if (!client.assertDebug()) {
if (__DEV__ && !options.debug) {
console.info(
'您当前处于开发环境且未启用debug不会进行热更检查。如需在开发环境中调试热更请在client中设置debug为true',
);
return;
}
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
if (autoMarkSuccess) {
setTimeout(() => {
markSuccess();
}, 1000);
markSuccess();
}
if (checkStrategy === 'both' || checkStrategy === 'onAppResume') {
stateListener.current = AppState.addEventListener(
@@ -276,10 +272,10 @@ export const UpdateProvider = ({
stateListener.current && stateListener.current.remove();
clearTimeout(dismissErrorTimer);
};
}, [checkUpdate, options, dismissError, markSuccess, client]);
}, [checkUpdate, options, dismissError, markSuccess]);
const parseTestPayload = useCallback(
(payload: UpdateTestPayload) => {
(payload: PushyTestPayload) => {
if (payload && payload.type && payload.type.startsWith('__rnPushy')) {
const logger = options.logger || (() => {});
options.logger = ({ type, data }) => {
@@ -290,8 +286,8 @@ export const UpdateProvider = ({
checkUpdate({ extra: { toHash: payload.data } }).then(() => {
if (updateInfoRef.current && updateInfoRef.current.upToDate) {
Alert.alert(
'Info',
'No update found, please wait 10s for the server to generate the patch package',
'提示',
'当前尚未检测到更新版本如果是首次扫码请等待服务器端生成补丁包后再试约10秒',
);
}
options.logger = logger;
@@ -305,7 +301,7 @@ export const UpdateProvider = ({
);
const parseTestQrCode = useCallback(
(code: string | UpdateTestPayload) => {
(code: string | PushyTestPayload) => {
try {
const payload = typeof code === 'string' ? JSON.parse(code) : code;
return parseTestPayload(payload);
@@ -330,21 +326,16 @@ export const UpdateProvider = ({
};
Linking.getInitialURL().then(parseLinking);
const linkingHandler = ({ url }: { url: string }) => {
parseLinking(url);
};
const linkingListener = Linking.addEventListener('url', linkingHandler);
const linkingListener = Linking.addEventListener('url', ({ url }) =>
parseLinking(url),
);
return () => {
if ('removeEventListener' in Linking) {
(Linking as any).removeEventListener('url', linkingHandler);
} else {
linkingListener.remove();
}
linkingListener.remove();
};
}, [parseTestPayload]);
return (
<UpdateContext.Provider
<PushyContext.Provider
value={{
checkUpdate,
switchVersion,
@@ -363,9 +354,6 @@ export const UpdateProvider = ({
parseTestQrCode,
}}>
{children}
</UpdateContext.Provider>
</PushyContext.Provider>
);
};
/** @deprecated Please use `UpdateProvider` instead */
export const PushyProvider = UpdateProvider;

View File

@@ -44,7 +44,7 @@ export type EventType =
export interface EventData {
currentVersion: string;
cInfo: {
rnu: string;
pushy: string;
rn: string;
os: string;
uuid: string;
@@ -65,15 +65,15 @@ export type UpdateEventsLogger = ({
data: EventData;
}) => void;
export interface UpdateServerConfig {
export interface PushyServerConfig {
main: string;
backups?: string[];
queryUrls?: string[];
}
export interface ClientOptions {
export interface PushyOptions {
appKey: string;
server?: UpdateServerConfig;
server?: PushyServerConfig;
logger?: UpdateEventsLogger;
updateStrategy?:
| 'alwaysAlert'
@@ -88,10 +88,9 @@ export interface ClientOptions {
throwError?: boolean;
beforeCheckUpdate?: () => Promise<boolean>;
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
afterDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
}
export interface UpdateTestPayload {
export interface PushyTestPayload {
type: '__rnPushyVersionHash' | string | null;
data: any;
}

View File

@@ -1,7 +1,7 @@
import { Platform } from 'react-native';
export function log(...args: any[]) {
console.log('react-native-update: ', ...args);
console.log('pushy: ', ...args);
}
export function promiseAny<T>(promises: Promise<T>[]) {
@@ -84,23 +84,3 @@ export const testUrls = async (urls?: string[]) => {
log('all ping failed, use first url:', urls[0]);
return urls[0];
};
export const assertWeb = () => {
if (Platform.OS === 'web') {
console.warn(
'react-native-update does not support the Web platform and will not perform any operations',
);
return false;
}
return true;
};
export const assertDev = (matter: string) => {
if (__DEV__) {
console.warn(
`${matter} is not supported in development environment; no action taken.`,
);
return false;
}
return true;
};