mirror of
https://gitcode.com/gh_mirrors/re/react-native-pushy.git
synced 2025-09-17 17:46:12 +08:00
Compare commits
73 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
05738ec204 | ||
![]() |
e4ef93595b | ||
![]() |
b336926838 | ||
![]() |
628647df98 | ||
![]() |
7d76034415 | ||
![]() |
ac217f659f | ||
![]() |
0e077b1de0 | ||
![]() |
1767fe37fa | ||
![]() |
7a9f579327 | ||
![]() |
350bfa0c89 | ||
![]() |
58ef3e6b22 | ||
![]() |
4dd89a1e74 | ||
![]() |
0019e9dd95 | ||
![]() |
90f6b7bcb3 | ||
![]() |
828740823d | ||
![]() |
135e0c5595 | ||
![]() |
06fc213da3 | ||
![]() |
a52d18dce2 | ||
![]() |
cef2b41a64 | ||
![]() |
fc5d248e2e | ||
![]() |
d5fd6c006d | ||
![]() |
26924d7e6c | ||
![]() |
3876110a66 | ||
![]() |
93f2d51c46 | ||
![]() |
4944b05378 | ||
![]() |
90d1539038 | ||
![]() |
26eacb923a | ||
![]() |
37739940ab | ||
![]() |
020e4f9239 | ||
![]() |
e0d4fe81fd | ||
![]() |
49b0c25a3d | ||
![]() |
10cb072fc3 | ||
![]() |
a432e5f1b1 | ||
![]() |
23d1fcd4d1 | ||
![]() |
e3a748065a | ||
![]() |
effd7e129d | ||
![]() |
9a00cf7483 | ||
![]() |
d854082495 | ||
![]() |
3073bd99db | ||
![]() |
4436654769 | ||
![]() |
3ccc3653ac | ||
![]() |
e150db486a | ||
![]() |
66c2504718 | ||
![]() |
bbda7217ac | ||
![]() |
0b52cf35d2 | ||
![]() |
46974ddb75 | ||
![]() |
0df6fa822b | ||
![]() |
fdb1fc304a | ||
![]() |
39ea11a435 | ||
![]() |
618a582e42 | ||
![]() |
31e6b0f5f0 | ||
![]() |
2a96684de7 | ||
![]() |
b04247b486 | ||
![]() |
828212f5bf | ||
![]() |
23ccfccdce | ||
![]() |
6943b3634e | ||
![]() |
1beb8762a7 | ||
![]() |
3ce7f0ff80 | ||
![]() |
bd5190331a | ||
![]() |
64b77d1b66 | ||
![]() |
a0adf1e778 | ||
![]() |
08547b7c8d | ||
![]() |
d355b37501 | ||
![]() |
ef9b773f41 | ||
![]() |
9eba54bdd4 | ||
![]() |
3d34410488 | ||
![]() |
9b9adc5d6a | ||
![]() |
964d66da74 | ||
![]() |
261427705c | ||
![]() |
f71419be45 | ||
![]() |
eabacaa1e3 | ||
![]() |
22d80890e2 | ||
![]() |
0df8261acb |
@@ -1,25 +1,16 @@
|
||||
## 运行harmony_use_pushy项目步骤
|
||||
|
||||
### 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++库进行初始化;
|
||||
### 1. 先在react-native-update根目录执行下面命令同步C++模块。
|
||||
```
|
||||
git submodule update --init --recursive
|
||||
yarn submodule
|
||||
```
|
||||
|
||||
### 4. 确保在react-native-update根目录已经执行过yarn submodule命令。
|
||||
说明:这个命令会在harmony/src/main/cpp目录生成HDiffPatch和lzma的C++模块依赖。
|
||||
|
||||
### 5. 在项目根目录执行下面命令安装第三方依赖。
|
||||
### 2. 在项目根目录执行下面命令安装第三方依赖。
|
||||
```
|
||||
yarn install
|
||||
```
|
||||
|
||||
### 6. 在项目根目录执行下面命令生成bundle包文件。
|
||||
### 3. 在项目根目录执行下面命令生成bundle包文件。
|
||||
```
|
||||
yarn build
|
||||
```
|
||||
@@ -27,8 +18,8 @@ yarn build
|
||||
|
||||
**注意⚠️**:在使用pushy bundle --platform harmony命令进行打包的默认bundle包名是Hbundle.harmony.js,不要随意修改包名,因为diff是匹配该包名进行生成的。
|
||||
|
||||
### 7. 使用DevEco Studio IDE打开harmony目录然后执行sync运行项目
|
||||
### 4. 使用DevEco Studio IDE打开harmony目录然后执行sync运行项目
|
||||

|
||||
|
||||
### 8 运行效果图
|
||||

|
||||
### 5 运行效果图
|
||||

|
||||
|
@@ -37,10 +37,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: 'rnoh',
|
||||
srcPath: '../libs/rnoh',
|
||||
},
|
||||
{
|
||||
name: 'pushy',
|
||||
srcPath: '../node_modules/react-native-update/harmony',
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { hapTasks } from '@ohos/hvigor-ohos-plugin';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export function generatePushyBuildTime(str?: string) {
|
||||
return {
|
||||
pluginId: 'PushyBuildTimePlugin',
|
||||
@@ -13,11 +14,22 @@ export function generatePushyBuildTime(str?: string) {
|
||||
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 };
|
||||
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']
|
||||
@@ -29,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. */
|
||||
}
|
||||
}
|
@@ -5,24 +5,25 @@
|
||||
"lockfileVersion": 3,
|
||||
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
|
||||
"specifiers": {
|
||||
"pushy@../../node_modules/react-native-update/harmony": "pushy@../../node_modules/react-native-update/harmony",
|
||||
"rnoh@../../libs/rnoh": "rnoh@../../libs/rnoh"
|
||||
"@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"
|
||||
},
|
||||
"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": "file:../../../libs/rnoh"
|
||||
"@rnoh/react-native-openharmony": "^0.72.38"
|
||||
}
|
||||
},
|
||||
"rnoh@../../libs/rnoh": {
|
||||
"name": "rnoh",
|
||||
"version": "0.72.12",
|
||||
"resolved": "../../libs/rnoh",
|
||||
"registryType": "local"
|
||||
}
|
||||
}
|
||||
}
|
@@ -6,7 +6,7 @@
|
||||
"author": "",
|
||||
"license": "",
|
||||
"dependencies": {
|
||||
"rnoh": "file:../../libs/rnoh",
|
||||
"@rnoh/react-native-openharmony": "0.72.38",
|
||||
"pushy": "file:../../node_modules/react-native-update/harmony"
|
||||
}
|
||||
}
|
||||
|
@@ -2,12 +2,23 @@ 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(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../libs/rnoh/src/main/cpp")
|
||||
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(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
|
||||
add_subdirectory("${OH_MODULES}/pushy/src/main/cpp" ./pushy)
|
||||
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"
|
||||
)
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import type {RNPackageContext, RNPackage} from 'rnoh/ts';
|
||||
import type {RNPackageContext, RNPackage} from '@rnoh/react-native-openharmony/ts';
|
||||
import {PushyPackage} from 'pushy/ts';
|
||||
|
||||
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import {RNAbility} from 'rnoh/ts';
|
||||
import {RNAbility} from '@rnoh/react-native-openharmony';
|
||||
|
||||
export default class EntryAbility extends RNAbility {
|
||||
getPagePath() {
|
||||
|
@@ -1,26 +1,32 @@
|
||||
import { FileJSBundleProvider } from 'pushy/src/main/ets/FileJSBundleProvider';
|
||||
import { ComponentBuilderContext, JSBundleProvider, RNOHLogger } from 'rnoh';
|
||||
import { ComponentBuilderContext, RNOHCoreContext,RNAbility } from '@rnoh/react-native-openharmony';
|
||||
import {
|
||||
RNApp,
|
||||
RNAbility,
|
||||
AnyJSBundleProvider,
|
||||
ResourceJSBundleProvider,
|
||||
TraceJSBundleProviderDecorator,
|
||||
} from 'rnoh'
|
||||
} from '@rnoh/react-native-openharmony'
|
||||
import { createRNPackages } from '../RNPackagesFactory'
|
||||
import preferences from '@ohos.data.preferences';
|
||||
|
||||
const arkTsComponentNames: Array<string> = [];
|
||||
|
||||
@Builder
|
||||
export function CustomComponentBuilder(ctx: ComponentBuilderContext) {
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
|
||||
const wrappedCustomRNComponentBuilder = wrapBuilder(buildCustomRNComponent)
|
||||
|
||||
@Entry
|
||||
@Component
|
||||
struct Index {
|
||||
@StorageLink('RNAbility') private rnAbility: RNAbility | undefined = undefined
|
||||
@StorageLink('RNOHCoreContext') private rnohCoreContext: RNOHCoreContext | undefined = undefined
|
||||
@State shouldShow: boolean = false
|
||||
@State message: string = 'Hello World';
|
||||
|
||||
aboutToAppear(): void {
|
||||
this.shouldShow = true
|
||||
@@ -30,28 +36,37 @@ 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
|
||||
return this.rnAbility?.onBackPress();
|
||||
this.rnohCoreContext!.dispatchBackPress()
|
||||
|
||||
// this.preferences = preferences.getPreferencesSync(this.context, {name:'update'});
|
||||
return true
|
||||
}
|
||||
|
||||
build() {
|
||||
Column() {
|
||||
if (this.rnAbility && this.shouldShow) {
|
||||
if (this.rnohCoreContext && this.shouldShow) {
|
||||
RNApp({
|
||||
rnInstanceConfig: { createRNPackages },
|
||||
rnInstanceConfig: {
|
||||
createRNPackages,
|
||||
enableNDKTextMeasuring: true,
|
||||
enableBackgroundExecutor: false,
|
||||
enableCAPIArchitecture: true,
|
||||
arkTsComponentNames: arkTsComponentNames,
|
||||
},
|
||||
initialProps: { "foo": "bar" } as Record<string, string>,
|
||||
appKey: "harmony_use_pushy",
|
||||
buildCustomComponent: CustomComponentBuilder,
|
||||
wrappedCustomRNComponentBuilder: wrappedCustomRNComponentBuilder,
|
||||
onSetUp: (rnInstance) => {
|
||||
rnInstance.enableFeatureFlag("ENABLE_RN_INSTANCE_CLEAN_UP")
|
||||
},
|
||||
jsBundleProvider: new TraceJSBundleProviderDecorator(
|
||||
new AnyJSBundleProvider([
|
||||
// MetroJSBundleProvider.fromServerIp('127.0.0.1'),
|
||||
// new ResourceJSBundleProvider(this.rnAbility.context.resourceManager, 'hermes_bundle.hbc'),
|
||||
new FileJSBundleProvider(this.rnAbility.context),
|
||||
new ResourceJSBundleProvider(this.rnAbility.context.resourceManager, 'bundle.harmony.js')
|
||||
// new ResourceJSBundleProvider(rnohCoreContext.uiAbilityContext.resourceManager, 'hermes_bundle.hbc'),
|
||||
new FileJSBundleProvider(this.rnohCoreContext.uiAbilityContext),
|
||||
new ResourceJSBundleProvider(this.rnohCoreContext.uiAbilityContext.resourceManager, 'bundle.harmony.js')
|
||||
]),
|
||||
this.rnAbility.getLogger()),
|
||||
this.rnohCoreContext.logger),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because one or more lines are too long
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"pushy_build_time": "2025-03-09T01:57:42.464Z",
|
||||
"versionName": "1.0.0"
|
||||
}
|
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"ios": {
|
||||
"appId": 24794,
|
||||
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
|
||||
},
|
||||
"android": {
|
||||
"appId": 27509,
|
||||
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
|
||||
},
|
||||
"harmony": {
|
||||
"appId": 29140,
|
||||
"appKey": "JLklGflGIRbY-cMebjQwm1J1"
|
||||
}
|
||||
}
|
@@ -13,5 +13,8 @@
|
||||
"suppressImplicitAnyIndexErrors": true,
|
||||
"strict": false
|
||||
}
|
||||
},
|
||||
"overrides": {
|
||||
"@rnoh/react-native-openharmony": "0.72.38"
|
||||
}
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@
|
||||
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
|
||||
},
|
||||
"harmony": {
|
||||
"appId": 29040,
|
||||
"appKey": "gdzeAqAFE5Jew15c5Df8EKU9"
|
||||
"appId": 29140,
|
||||
"appKey": "JLklGflGIRbY-cMebjQwm1J1"
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
1
Example/testHotUpdate/.gitignore
vendored
1
Example/testHotUpdate/.gitignore
vendored
@@ -30,6 +30,7 @@ build/
|
||||
local.properties
|
||||
*.iml
|
||||
*.hprof
|
||||
.kotlin/
|
||||
|
||||
# node.js
|
||||
#
|
||||
|
@@ -1 +0,0 @@
|
||||
18
|
@@ -68,12 +68,12 @@ 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 = 'org.webkit:android-jsc:+'
|
||||
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
|
||||
|
||||
android {
|
||||
ndkVersion rootProject.ext.ndkVersion
|
||||
|
||||
compileSdkVersion rootProject.ext.compileSdkVersion
|
||||
buildToolsVersion rootProject.ext.buildToolsVersion
|
||||
compileSdk rootProject.ext.compileSdkVersion
|
||||
|
||||
namespace "com.awesomeproject"
|
||||
defaultConfig {
|
||||
|
@@ -2,12 +2,8 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
|
||||
|
||||
<application
|
||||
android:usesCleartextTraffic="true"
|
||||
tools:targetApi="28"
|
||||
tools:ignore="GoogleAppIndexingWarning">
|
||||
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false" />
|
||||
</application>
|
||||
tools:ignore="GoogleAppIndexingWarning"/>
|
||||
</manifest>
|
||||
|
@@ -1,5 +1,4 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.awesomeproject">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
@@ -1,32 +0,0 @@
|
||||
package com.awesomeproject;
|
||||
|
||||
import com.facebook.react.ReactActivity;
|
||||
import com.facebook.react.ReactActivityDelegate;
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
|
||||
import com.facebook.react.defaults.DefaultReactActivityDelegate;
|
||||
|
||||
public class MainActivity extends ReactActivity {
|
||||
|
||||
/**
|
||||
* Returns the name of the main component registered from JavaScript. This is used to schedule
|
||||
* rendering of the component.
|
||||
*/
|
||||
@Override
|
||||
protected String getMainComponentName() {
|
||||
return "AwesomeProject";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
|
||||
* DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
|
||||
* (aka React 18) with two boolean flags.
|
||||
*/
|
||||
@Override
|
||||
protected ReactActivityDelegate createReactActivityDelegate() {
|
||||
return new DefaultReactActivityDelegate(
|
||||
this,
|
||||
getMainComponentName(),
|
||||
// If you opted-in for the New Architecture, we enable the Fabric Renderer.
|
||||
DefaultNewArchitectureEntryPoint.getFabricEnabled());
|
||||
}
|
||||
}
|
@@ -0,0 +1,22 @@
|
||||
package com.awesomeproject
|
||||
|
||||
import com.facebook.react.ReactActivity
|
||||
import com.facebook.react.ReactActivityDelegate
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
|
||||
import com.facebook.react.defaults.DefaultReactActivityDelegate
|
||||
|
||||
class MainActivity : ReactActivity() {
|
||||
|
||||
/**
|
||||
* Returns the name of the main component registered from JavaScript. This is used to schedule
|
||||
* rendering of the component.
|
||||
*/
|
||||
override fun getMainComponentName(): String = "AwesomeProject"
|
||||
|
||||
/**
|
||||
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
|
||||
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
|
||||
*/
|
||||
override fun createReactActivityDelegate(): ReactActivityDelegate =
|
||||
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
|
||||
}
|
@@ -1,69 +0,0 @@
|
||||
package com.awesomeproject;
|
||||
|
||||
import android.app.Application;
|
||||
import com.facebook.react.PackageList;
|
||||
import com.facebook.react.ReactApplication;
|
||||
import com.facebook.react.ReactNativeHost;
|
||||
import com.facebook.react.ReactPackage;
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
|
||||
import com.facebook.react.defaults.DefaultReactNativeHost;
|
||||
import com.facebook.soloader.SoLoader;
|
||||
import java.util.List;
|
||||
import cn.reactnative.modules.update.UpdateContext;
|
||||
|
||||
public class MainApplication extends Application implements ReactApplication {
|
||||
|
||||
private final ReactNativeHost mReactNativeHost =
|
||||
new DefaultReactNativeHost(this) {
|
||||
@Override
|
||||
public boolean getUseDeveloperSupport() {
|
||||
return BuildConfig.DEBUG;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getJSBundleFile() {
|
||||
return UpdateContext.getBundleUrl(MainApplication.this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<ReactPackage> getPackages() {
|
||||
@SuppressWarnings("UnnecessaryLocalVariable")
|
||||
List<ReactPackage> packages = new PackageList(this).getPackages();
|
||||
// Packages that cannot be autolinked yet can be added manually here, for example:
|
||||
// packages.add(new MyReactNativePackage());
|
||||
return packages;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isNewArchEnabled() {
|
||||
return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Boolean isHermesEnabled() {
|
||||
return BuildConfig.IS_HERMES_ENABLED;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected String getJSMainModuleName() {
|
||||
return "index";
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@Override
|
||||
public ReactNativeHost getReactNativeHost() {
|
||||
return mReactNativeHost;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
SoLoader.init(this, /* native exopackage */ false);
|
||||
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
|
||||
// If you opted-in for the New Architecture, we load the native entry point for this app.
|
||||
DefaultNewArchitectureEntryPoint.load();
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,48 @@
|
||||
package com.awesomeproject
|
||||
|
||||
import android.app.Application
|
||||
import cn.reactnative.modules.update.UpdateContext
|
||||
import com.facebook.react.PackageList
|
||||
import com.facebook.react.ReactApplication
|
||||
import com.facebook.react.ReactHost
|
||||
import com.facebook.react.ReactNativeHost
|
||||
import com.facebook.react.ReactPackage
|
||||
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
|
||||
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
|
||||
import com.facebook.react.defaults.DefaultReactNativeHost
|
||||
import com.facebook.react.soloader.OpenSourceMergedSoMapping
|
||||
import com.facebook.soloader.SoLoader
|
||||
|
||||
class MainApplication : Application(), ReactApplication {
|
||||
|
||||
override val reactNativeHost: ReactNativeHost =
|
||||
object : DefaultReactNativeHost(this) {
|
||||
|
||||
override fun getJSBundleFile(): String? = UpdateContext.getBundleUrl(this@MainApplication)
|
||||
|
||||
override fun getPackages(): List<ReactPackage> =
|
||||
PackageList(this).packages.apply {
|
||||
// Packages that cannot be autolinked yet can be added manually here, for example:
|
||||
// add(MyReactNativePackage())
|
||||
}
|
||||
|
||||
override fun getJSMainModuleName(): String = "index"
|
||||
|
||||
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
|
||||
|
||||
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
|
||||
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
|
||||
}
|
||||
|
||||
override val reactHost: ReactHost
|
||||
get() = getDefaultReactHost(applicationContext, reactNativeHost)
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
SoLoader.init(this, OpenSourceMergedSoMapping)
|
||||
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
|
||||
// If you opted-in for the New Architecture, we load the native entry point for this app.
|
||||
load()
|
||||
}
|
||||
}
|
||||
}
|
@@ -3,9 +3,9 @@ buildscript {
|
||||
buildToolsVersion = "35.0.0"
|
||||
minSdkVersion = 24
|
||||
compileSdkVersion = 35
|
||||
targetSdkVersion = 34
|
||||
ndkVersion = "26.1.10909125"
|
||||
kotlinVersion = "1.9.24"
|
||||
targetSdkVersion = 35
|
||||
ndkVersion = "27.1.12297006"
|
||||
kotlinVersion = "2.0.21"
|
||||
}
|
||||
repositories {
|
||||
google()
|
||||
|
@@ -1,6 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
|
3
Example/testHotUpdate/android/gradlew
vendored
3
Example/testHotUpdate/android/gradlew
vendored
@@ -86,8 +86,7 @@ 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
|
||||
' "$PWD" ) || exit
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
@@ -2,6 +2,5 @@ pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
|
||||
plugins { id("com.facebook.react.settings") }
|
||||
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
|
||||
rootProject.name = 'AwesomeProject'
|
||||
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
|
||||
include ':app'
|
||||
includeBuild('../node_modules/@react-native/gradle-plugin')
|
||||
|
650
Example/testHotUpdate/bun.lock
Executable file → Normal file
650
Example/testHotUpdate/bun.lock
Executable file → Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');
|
||||
* Metro configuration
|
||||
* https://reactnative.dev/docs/metro
|
||||
*
|
||||
* @type {import('metro-config').MetroConfig}
|
||||
* @type {import('@react-native/metro-config').MetroConfig}
|
||||
*/
|
||||
const config = {};
|
||||
|
||||
|
@@ -14,41 +14,42 @@
|
||||
"dev:harmony": "react-native bundle-harmony --dev"
|
||||
},
|
||||
"dependencies": {
|
||||
"form-data": "^4.0.1",
|
||||
"form-data": "^4.0.2",
|
||||
"patch-package": "^8.0.0",
|
||||
"postinstall-postinstall": "^2.1.0",
|
||||
"react": "18.3.1",
|
||||
"react-native": "0.76.3",
|
||||
"react-native-camera-kit": "^14.1.0",
|
||||
"react-native-paper": "^5.12.5",
|
||||
"react-native-safe-area-context": "^4.14.0",
|
||||
"react-native-update": "^10.17.1",
|
||||
"react": "19.0.0",
|
||||
"react-native": "0.78.0",
|
||||
"react-native-camera-kit": "^14.2.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-vector-icons": "^10.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.26.0",
|
||||
"@babel/preset-env": "^7.26.0",
|
||||
"@babel/runtime": "^7.26.0",
|
||||
"@react-native-community/cli": "15.0.0-alpha.2",
|
||||
"@react-native-community/cli-platform-android": "15.0.0-alpha.2",
|
||||
"@react-native-community/cli-platform-ios": "15.0.0-alpha.2",
|
||||
"@react-native/babel-preset": "0.76.3",
|
||||
"@react-native/eslint-config": "0.76.3",
|
||||
"@react-native/metro-config": "0.76.3",
|
||||
"@react-native/typescript-config": "0.76.3",
|
||||
"@types/react": "^18.2.6",
|
||||
"@types/react-test-renderer": "^18.0.0",
|
||||
"babel-jest": "^29.6.3",
|
||||
"@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",
|
||||
"detox": "^20.32.0",
|
||||
"eslint": "^8.19.0",
|
||||
"jest": "^29.6.3",
|
||||
"prettier": "2.8.8",
|
||||
"react-test-renderer": "18.3.1",
|
||||
"typescript": "5.7.2"
|
||||
"react-test-renderer": "19.0.0",
|
||||
"typescript": "5.8.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
"node": ">=18"
|
||||
},
|
||||
"trustedDependencies": [
|
||||
"postinstall-postinstall"
|
||||
"detox",
|
||||
"dtrace-provider"
|
||||
]
|
||||
}
|
||||
}
|
9
Example/testHotUpdate/src/assets/react-logo.svg
Normal file
9
Example/testHotUpdate/src/assets/react-logo.svg
Normal file
@@ -0,0 +1,9 @@
|
||||
<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>
|
After Width: | Height: | Size: 365 B |
@@ -20,11 +20,12 @@ 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 {PushyProvider, Pushy, usePushy} from 'react-native-update';
|
||||
import {UpdateProvider, Pushy, Cresc, useUpdate} from 'react-native-update';
|
||||
const {appKey} = _updateConfig[Platform.OS];
|
||||
|
||||
function App() {
|
||||
@@ -39,7 +40,7 @@ function App() {
|
||||
currentHash,
|
||||
parseTestQrCode,
|
||||
progress: {received, total} = {},
|
||||
} = usePushy();
|
||||
} = useUpdate();
|
||||
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
|
||||
const [showTestConsole, setShowTestConsole] = useState(false);
|
||||
const [showUpdateBanner, setShowUpdateBanner] = useState(false);
|
||||
@@ -91,11 +92,21 @@ function App() {
|
||||
/>
|
||||
</Modal>
|
||||
</Portal>
|
||||
<Image
|
||||
resizeMode={'contain'}
|
||||
source={require('./assets/shezhi.png')}
|
||||
style={styles.image}
|
||||
/>
|
||||
<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>
|
||||
<Text style={styles.instructions}>
|
||||
这是版本一 {'\n'}
|
||||
当前原生包版本号: {packageVersion}
|
||||
@@ -192,17 +203,25 @@ const styles = StyleSheet.create({
|
||||
image: {},
|
||||
});
|
||||
|
||||
const pushyClient = new Pushy({
|
||||
// use Pushy for China users
|
||||
const updateClient = new Pushy({
|
||||
appKey,
|
||||
debug: true,
|
||||
// updateStrategy: 'silentAndLater',
|
||||
});
|
||||
|
||||
// use Cresc for global users
|
||||
// const updateClient = new Cresc({
|
||||
// appKey,
|
||||
// debug: true,
|
||||
// });
|
||||
|
||||
export default function Root() {
|
||||
return (
|
||||
<PushyProvider client={pushyClient}>
|
||||
<UpdateProvider client={updateClient}>
|
||||
<PaperProvider>
|
||||
<App />
|
||||
</PaperProvider>
|
||||
</PushyProvider>
|
||||
</UpdateProvider>
|
||||
);
|
||||
}
|
||||
}
|
@@ -7,4 +7,4 @@
|
||||
"appId": 27509,
|
||||
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
|
||||
}
|
||||
}
|
||||
}
|
@@ -2,6 +2,8 @@
|
||||
|
||||
本组件是面向 React Native 提供热更新功能的组件,详情请访问我们的官方网站 <https://pushy.reactnative.cn>。
|
||||
|
||||
**现已支持鸿蒙以及新架构**
|
||||
|
||||
### 快速开始
|
||||
|
||||
请查看[文档](https://pushy.reactnative.cn/docs/getting-started.html)
|
||||
@@ -20,7 +22,7 @@
|
||||
### 本地开发
|
||||
|
||||
```
|
||||
$ git clone git@github.com:reactnativecn/react-native-pushy.git
|
||||
$ git clone git@github.com:reactnativecn/react-native-update.git
|
||||
$ cd react-native-pushy/Example/testHotUpdate
|
||||
$ yarn
|
||||
$ yarn start
|
||||
@@ -32,4 +34,4 @@ $ yarn start
|
||||
|
||||
本组件由[React Native 中文网](https://reactnative.cn/)独家发布,如有定制需求可以[联系我们](https://reactnative.cn/about.html#content)。
|
||||
|
||||
关于此插件发现任何问题,可以前往[Issues](https://github.com/reactnativecn/react-native-pushy/issues)发帖提问。
|
||||
关于此插件发现任何问题,可以前往[Issues](https://github.com/reactnativecn/react-native-update/issues)发帖提问。
|
||||
|
@@ -22,14 +22,42 @@ def supportsNamespace() {
|
||||
return major >= 8
|
||||
}
|
||||
|
||||
def isExpoProject() {
|
||||
def hasExpoModulesCore = rootProject.subprojects.any { it.name == 'expo-modules-core' }
|
||||
|
||||
def packageJsonFile = new File(rootProject.projectDir.parentFile, 'package.json')
|
||||
def hasExpoDependency = false
|
||||
if (packageJsonFile.exists()) {
|
||||
def packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
|
||||
hasExpoDependency = (packageJson.dependencies?.expo != null) ||
|
||||
(packageJson.devDependencies?.expo != null)
|
||||
}
|
||||
|
||||
return hasExpoModulesCore || hasExpoDependency
|
||||
}
|
||||
|
||||
def expoProject = isExpoProject()
|
||||
|
||||
apply plugin: 'com.android.library'
|
||||
if (isNewArchitectureEnabled()) {
|
||||
apply plugin: 'com.facebook.react'
|
||||
}
|
||||
|
||||
if (expoProject) {
|
||||
group = 'expo.modules.pushy'
|
||||
version = '1.0.0'
|
||||
|
||||
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
|
||||
apply from: expoModulesCorePlugin
|
||||
applyKotlinExpoModulesCorePlugin()
|
||||
useCoreDependencies()
|
||||
useExpoPublishing()
|
||||
} else {
|
||||
group = 'cn.reactnative.modules.update'
|
||||
version = '1.0.0'
|
||||
}
|
||||
|
||||
android {
|
||||
|
||||
if (supportsNamespace()) {
|
||||
namespace "cn.reactnative.modules.update"
|
||||
|
||||
@@ -41,7 +69,6 @@ android {
|
||||
}
|
||||
compileSdkVersion safeExtGet('compileSdkVersion', 28)
|
||||
buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3')
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion safeExtGet('minSdkVersion', 16)
|
||||
targetSdkVersion safeExtGet('targetSdkVersion', 27)
|
||||
@@ -50,6 +77,7 @@ android {
|
||||
consumerProguardFiles "proguard.pro"
|
||||
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
main {
|
||||
// let gradle pack the shared library into apk
|
||||
@@ -59,6 +87,12 @@ android {
|
||||
} else {
|
||||
java.srcDirs += ['src/oldarch']
|
||||
}
|
||||
|
||||
if (expoProject) {
|
||||
java.srcDirs += ['java/expo/modules/pushy']
|
||||
} else {
|
||||
java.exclude 'expo/modules/pushy/**'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +104,10 @@ android {
|
||||
resValue("string", "pushy_build_time", "0")
|
||||
}
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
abortOnError false
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
|
@@ -49,7 +49,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
||||
|
||||
private void removeDirectory(File file) throws IOException {
|
||||
if (UpdateContext.DEBUG) {
|
||||
Log.d("RNUpdate", "Removing " + file);
|
||||
Log.d("react-native-update", "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("RNUpdate", "Downloading " + url);
|
||||
Log.d("react-native-update", "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("RNUpdate", "Progress " + received + "/" + contentLength);
|
||||
Log.d("react-native-update", "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("RNUpdate", "Download finished");
|
||||
Log.d("react-native-update", "Download finished");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,7 +244,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
|
||||
|
||||
|
||||
if (UpdateContext.DEBUG) {
|
||||
Log.d("RNUpdate", "Unzip finished");
|
||||
Log.d("react-native-update", "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("RNUpdate", "Copying from resource " + fn + " to " + target);
|
||||
Log.d("react-native-update", "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("RNUpdate", "Unzip finished");
|
||||
Log.d("react-native-update", "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("RNUpdate", "Unzip finished");
|
||||
Log.d("react-native-update", "Unzip finished");
|
||||
}
|
||||
}
|
||||
private void doCleanUp(DownloadTaskParams param) throws IOException {
|
||||
if (UpdateContext.DEBUG) {
|
||||
Log.d("RNUpdate", "Start cleaning up");
|
||||
Log.d("react-native-update", "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("pushy", "download task failed", e);
|
||||
Log.e("react-native-update", "download task failed", e);
|
||||
|
||||
if (params[0].listener != null) {
|
||||
params[0].listener.onDownloadFailed(e);
|
||||
|
@@ -0,0 +1,13 @@
|
||||
package cn.reactnative.modules.update;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
public interface ReactNativeHostHandler {
|
||||
@Nullable
|
||||
String getJSBundleFile(boolean useDeveloperSupport);
|
||||
|
||||
@Nullable
|
||||
String getBundleAssetName(boolean useDeveloperSupport);
|
||||
|
||||
void onWillCreateReactInstance(boolean useDeveloperSupport);
|
||||
}
|
@@ -7,14 +7,11 @@ import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
|
||||
import com.facebook.react.ReactInstanceManager;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class UpdateContext {
|
||||
|
@@ -3,7 +3,10 @@ package cn.reactnative.modules.update;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.facebook.react.ReactActivity;
|
||||
import com.facebook.react.ReactApplication;
|
||||
import com.facebook.react.ReactDelegate;
|
||||
import com.facebook.react.ReactInstanceManager;
|
||||
import com.facebook.react.bridge.JSBundleLoader;
|
||||
import com.facebook.react.bridge.Promise;
|
||||
@@ -12,16 +15,10 @@ import com.facebook.react.bridge.ReadableMap;
|
||||
import com.facebook.react.bridge.UiThreadUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class UpdateModuleImpl {
|
||||
|
||||
@@ -101,37 +98,20 @@ public class UpdateModuleImpl {
|
||||
}
|
||||
});
|
||||
}catch (Exception e){
|
||||
promise.reject("执行报错:"+e.getMessage());
|
||||
promise.reject("downloadPatchFromPpk failed: "+e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void loadBundleLegacy(ReactApplicationContext mContext) {
|
||||
final Activity currentActivity = mContext.getCurrentActivity();
|
||||
if (currentActivity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
currentActivity.recreate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void reloadUpdate(UpdateContext updateContext, ReactApplicationContext mContext, ReadableMap options,Promise promise) {
|
||||
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) {
|
||||
@@ -139,12 +119,10 @@ 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));
|
||||
@@ -154,76 +132,122 @@ public class UpdateModuleImpl {
|
||||
promise.resolve(true);
|
||||
|
||||
} catch (Throwable err) {
|
||||
promise.reject(err);
|
||||
Log.e("pushy", "switchVersion failed ", err);
|
||||
loadBundleLegacy(mContext);
|
||||
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");
|
||||
} catch (Throwable e) {
|
||||
currentActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
currentActivity.recreate();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
promise.resolve(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void restartApp(final ReactApplicationContext mContext, Promise promise) {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
final Context application = mContext.getApplicationContext();
|
||||
ReactInstanceManager instanceManager = ((ReactApplication) application).getReactNativeHost().getReactInstanceManager();
|
||||
|
||||
instanceManager.recreateReactContextInBackground();
|
||||
promise.resolve(true);
|
||||
|
||||
} catch (Throwable err) {
|
||||
promise.reject("restartApp failed: "+err.getMessage());
|
||||
Log.e("pushy", "restartApp failed", err);
|
||||
|
||||
final Activity currentActivity = mContext.getCurrentActivity();
|
||||
if (currentActivity == null) {
|
||||
return;
|
||||
}
|
||||
currentActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
currentActivity.recreate();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
public static void markSuccess(UpdateContext updateContext, Promise promise) {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateContext.markSuccess();
|
||||
promise.resolve(true);
|
||||
}
|
||||
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) {
|
||||
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) {
|
||||
try {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateContext.setKv("uuid", uuid);
|
||||
promise.resolve(true);
|
||||
}
|
||||
});
|
||||
} catch (Exception e){
|
||||
promise.reject("执行报错:"+e.getMessage());
|
||||
}
|
||||
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
updateContext.setKv("uuid", uuid);
|
||||
promise.resolve(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -233,12 +257,12 @@ public class UpdateModuleImpl {
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if(!check(info)){
|
||||
updateContext.setKv("hash_" + hash, info);
|
||||
promise.reject("校验报错:json字符串格式错误");
|
||||
}else {
|
||||
if (check(info)) {
|
||||
updateContext.setKv("hash_" + hash, info);
|
||||
promise.resolve(true);
|
||||
} else {
|
||||
updateContext.setKv("hash_" + hash, info);
|
||||
promise.reject("setLocalHashInfo failed: invalid json string");
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -249,7 +273,7 @@ public class UpdateModuleImpl {
|
||||
if (check(value)) {
|
||||
promise.resolve(value);
|
||||
} else {
|
||||
promise.reject("校验报错:json字符串格式错误");
|
||||
promise.reject("getLocalHashInfo failed: invalid json string");
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -9,9 +9,6 @@ import com.facebook.react.module.model.ReactModuleInfoProvider;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by tdzl2003 on 3/31/16.
|
||||
*/
|
||||
public class UpdatePackage extends TurboReactPackage {
|
||||
@Nullable
|
||||
@Override
|
||||
@@ -25,21 +22,24 @@ public class UpdatePackage extends TurboReactPackage {
|
||||
|
||||
@Override
|
||||
public ReactModuleInfoProvider getReactModuleInfoProvider() {
|
||||
return () -> {
|
||||
final Map<String, ReactModuleInfo> moduleInfos = new HashMap<>();
|
||||
boolean isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
|
||||
moduleInfos.put(
|
||||
UpdateModuleImpl.NAME,
|
||||
new ReactModuleInfo(
|
||||
UpdateModuleImpl.NAME,
|
||||
UpdateModuleImpl.NAME,
|
||||
false, // canOverrideExistingModule
|
||||
false, // needsEagerInit
|
||||
true, // hasConstants
|
||||
false, // isCxxModule
|
||||
isTurboModule // isTurboModule
|
||||
));
|
||||
return moduleInfos;
|
||||
return new ReactModuleInfoProvider() {
|
||||
@Override
|
||||
public Map<String, ReactModuleInfo> getReactModuleInfos() {
|
||||
final Map<String, ReactModuleInfo> moduleInfos = new HashMap<>();
|
||||
boolean isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
|
||||
moduleInfos.put(
|
||||
UpdateModuleImpl.NAME,
|
||||
new ReactModuleInfo(
|
||||
UpdateModuleImpl.NAME,
|
||||
UpdateModuleImpl.NAME,
|
||||
false, // canOverrideExistingModule
|
||||
false, // needsEagerInit
|
||||
true, // hasConstants
|
||||
false, // isCxxModule
|
||||
isTurboModule // isTurboModule
|
||||
));
|
||||
return moduleInfos;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
10
android/src/main/java/expo/modules/pushy/ExpoPushyModule.kt
Normal file
10
android/src/main/java/expo/modules/pushy/ExpoPushyModule.kt
Normal file
@@ -0,0 +1,10 @@
|
||||
package expo.modules.pushy
|
||||
|
||||
import expo.modules.kotlin.modules.Module
|
||||
import expo.modules.kotlin.modules.ModuleDefinition
|
||||
|
||||
class ExpoPushyModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("ExpoPushy")
|
||||
}
|
||||
}
|
@@ -0,0 +1,27 @@
|
||||
package expo.modules.pushy;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
import androidx.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import cn.reactnative.modules.update.UpdateContext;
|
||||
import expo.modules.core.interfaces.Package;
|
||||
import expo.modules.core.interfaces.ReactNativeHostHandler;
|
||||
|
||||
public class ExpoPushyPackage implements Package {
|
||||
@Override
|
||||
public List<ReactNativeHostHandler> createReactNativeHostHandlers(Context context) {
|
||||
List<ReactNativeHostHandler> handlers = new ArrayList<>();
|
||||
handlers.add(new ReactNativeHostHandler() {
|
||||
@Nullable
|
||||
@Override
|
||||
public String getJSBundleFile(boolean useDeveloperSupport) {
|
||||
return UpdateContext.getBundleUrl(context);
|
||||
}
|
||||
});
|
||||
return handlers;
|
||||
}
|
||||
}
|
@@ -97,6 +97,11 @@ public class UpdateModule extends NativePushySpec {
|
||||
UpdateModuleImpl.reloadUpdate(updateContext, mContext, options,promise);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void restartApp(Promise promise) {
|
||||
UpdateModuleImpl.restartApp(mContext, promise);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNeedUpdate(ReadableMap options,Promise promise) {
|
||||
UpdateModuleImpl.setNeedUpdate(updateContext, options,promise);
|
||||
|
@@ -224,6 +224,29 @@ public class UpdateModule extends ReactContextBaseJavaModule {
|
||||
});
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void restartApp(final Promise promise) {
|
||||
|
||||
UiThreadUtil.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
final Context application = getReactApplicationContext().getApplicationContext();
|
||||
ReactInstanceManager instanceManager = updateContext.getCustomReactInstanceManager();
|
||||
if (instanceManager == null) {
|
||||
instanceManager = ((ReactApplication) application).getReactNativeHost().getReactInstanceManager();
|
||||
}
|
||||
instanceManager.recreateReactContextInBackground();
|
||||
promise.resolve(true);
|
||||
|
||||
} catch (Throwable err) {
|
||||
promise.reject(err);
|
||||
Log.e("pushy", "restartApp failed ", err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ReactMethod
|
||||
public void setNeedUpdate(ReadableMap options) {
|
||||
final String hash = options.getString("hash");
|
||||
|
1
endpoints_cresc.json
Normal file
1
endpoints_cresc.json
Normal file
@@ -0,0 +1 @@
|
||||
["https://cresc-server-pthxtmvcnf.ap-southeast-1.fcapp.run"]
|
13
expo-module.config.json
Normal file
13
expo-module.config.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"platforms": ["apple", "android"],
|
||||
"apple": {
|
||||
"modules": ["ExpoPushyModule"],
|
||||
"reactDelegateHandlers": ["ExpoPushyReactDelegateHandler"],
|
||||
"podspecPath":"react-native-update.podspec"
|
||||
},
|
||||
"android": {
|
||||
"modules": [
|
||||
"expo.modules.pushy.ExpoPushyModule"
|
||||
]
|
||||
}
|
||||
}
|
@@ -1,11 +0,0 @@
|
||||
[
|
||||
{
|
||||
"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 type,Connection quality"
|
||||
}
|
||||
]
|
@@ -5,14 +5,15 @@
|
||||
"lockfileVersion": 3,
|
||||
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
|
||||
"specifiers": {
|
||||
"rnoh@../../../libs/rnoh": "rnoh@../../../libs/rnoh"
|
||||
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38"
|
||||
},
|
||||
"packages": {
|
||||
"rnoh@../../../libs/rnoh": {
|
||||
"name": "rnoh",
|
||||
"version": "0.72.12",
|
||||
"resolved": "../../../libs/rnoh",
|
||||
"registryType": "local"
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
}
|
@@ -7,6 +7,6 @@
|
||||
"main": "index.ets",
|
||||
"version": "3.1.0-0.0.7",
|
||||
"dependencies": {
|
||||
"rnoh": "file:../../../libs/rnoh"
|
||||
"@rnoh/react-native-openharmony":"^0.72.38"
|
||||
}
|
||||
}
|
||||
|
1
harmony/oh_modules/@rnoh/react-native-openharmony
Symbolic link
1
harmony/oh_modules/@rnoh/react-native-openharmony
Symbolic link
@@ -0,0 +1 @@
|
||||
../../../../../harmony/oh_modules/.ohpm/@rnoh+react-native-openharmony@0.72.38/oh_modules/@rnoh/react-native-openharmony
|
@@ -72,16 +72,18 @@ napi_value HdiffPatch(napi_env env, napi_callback_info info) {
|
||||
// 创建结果buffer
|
||||
napi_value resultBuffer;
|
||||
uint8_t* outPtr;
|
||||
status = napi_create_buffer(env, newsize, (void**)&outPtr, &resultBuffer);
|
||||
void* data;
|
||||
|
||||
status = napi_create_arraybuffer(env, newsize, &data, &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:
|
||||
|
@@ -65,9 +65,13 @@ export class DownloadTask {
|
||||
0,
|
||||
params.targetFile.lastIndexOf('/'),
|
||||
);
|
||||
await fileIo.mkdir(targetDir);
|
||||
const exists = fileIo.accessSync(targetDir);
|
||||
if(!exists){
|
||||
await fileIo.mkdir(targetDir);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const response = await httpRequest.request(params.url, {
|
||||
@@ -78,12 +82,11 @@ 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,
|
||||
@@ -102,8 +105,12 @@ export class DownloadTask {
|
||||
this.onProgressUpdate(received, contentLength);
|
||||
}
|
||||
await fileIo.close(writer);
|
||||
const stat = await fileIo.stat(params.targetFile);
|
||||
const fileSize = stat.size;
|
||||
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`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Download failed:', error);
|
||||
throw error;
|
||||
@@ -113,7 +120,7 @@ export class DownloadTask {
|
||||
}
|
||||
|
||||
private onProgressUpdate(received: number, total: number): void {
|
||||
this.eventHub.emit('downloadProgress', {
|
||||
this.eventHub.emit('RCTPushyDownloadProgress', {
|
||||
received,
|
||||
total,
|
||||
hash: this.hash,
|
||||
@@ -288,7 +295,9 @@ export class DownloadTask {
|
||||
}
|
||||
}
|
||||
|
||||
await zip.decompressFile(entry.filename, params.unzipDirectory);
|
||||
if(fn !== '.DS_Store'){
|
||||
await zip.decompressFile(fn, params.unzipDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundDiff) {
|
||||
|
@@ -3,6 +3,7 @@ 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();
|
||||
@@ -27,12 +28,12 @@ export class EventHub {
|
||||
}
|
||||
|
||||
public emit(event: string, data: any): void {
|
||||
this.listeners.get(event)?.forEach(callback => {
|
||||
try {
|
||||
callback(data);
|
||||
} catch (error) {
|
||||
console.error(`Error in event listener for ${event}:`, error);
|
||||
}
|
||||
});
|
||||
if (this.rnInstance) {
|
||||
this.rnInstance.emitDeviceEvent(event, data);
|
||||
}
|
||||
}
|
||||
|
||||
setRNInstance(instance: any) {
|
||||
this.rnInstance = instance;
|
||||
}
|
||||
}
|
@@ -1,4 +1,4 @@
|
||||
import { HotReloadConfig, JSBundleProvider, JSBundleProviderError, JSPackagerClientConfig } from 'rnoh';
|
||||
import { HotReloadConfig, JSBundleProvider, JSBundleProviderError, JSPackagerClientConfig } from '@rnoh/react-native-openharmony';
|
||||
import fileIo from '@ohos.file.fs';
|
||||
import common from '@ohos.app.ability.common';
|
||||
import { UpdateContext } from './UpdateContext';
|
||||
@@ -40,20 +40,15 @@ export class FileJSBundleProvider extends JSBundleProvider {
|
||||
}
|
||||
throw new Error('Update bundle not found');
|
||||
} catch (error) {
|
||||
throw new JSBundleProviderError(`Couldn't load JSBundle from ${this.filePath}`, 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.`]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
getAppKeys(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
getHotReloadConfig(): HotReloadConfig | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
getJSPackagerClientConfig(): JSPackagerClientConfig | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
import { RNPackage, TurboModulesFactory } from 'rnoh/ts';
|
||||
import type { TurboModule, TurboModuleContext } from 'rnoh/ts';
|
||||
import { RNPackage, TurboModulesFactory } from '@rnoh/react-native-openharmony/ts';
|
||||
import type { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
|
||||
import { PushyTurboModule } from './PushyTurboModule';
|
||||
|
||||
class PushyTurboModulesFactory extends TurboModulesFactory {
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import { TurboModule, TurboModuleContext } from 'rnoh/ts';
|
||||
import { TurboModule, TurboModuleContext } from '@rnoh/react-native-openharmony/ts';
|
||||
import common from '@ohos.app.ability.common';
|
||||
import dataPreferences from '@ohos.data.preferences';
|
||||
import { bundleManager } from '@kit.AbilityKit';
|
||||
@@ -7,6 +7,7 @@ import { BusinessError } from '@ohos.base';
|
||||
import logger from './Logger';
|
||||
import { UpdateModuleImpl } from './UpdateModuleImpl';
|
||||
import { UpdateContext } from './UpdateContext';
|
||||
import { EventHub } from './EventHub';
|
||||
|
||||
const TAG = "PushyTurboModule"
|
||||
|
||||
@@ -18,9 +19,8 @@ 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)
|
||||
// rnInstance.emitDeviceEvent("Pushy",{code: err.code, message: err.message});
|
||||
EventHub.getInstance().setRNInstance(ctx.rnInstance)
|
||||
}
|
||||
|
||||
|
||||
|
@@ -26,15 +26,18 @@ export class UpdateContext {
|
||||
this.initPreferences();
|
||||
}
|
||||
|
||||
private async initPreferences() {
|
||||
private initPreferences() {
|
||||
try {
|
||||
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.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.cleanUp();
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -42,33 +45,33 @@ export class UpdateContext {
|
||||
}
|
||||
}
|
||||
|
||||
public async setKv(key: string, value: string): Promise<void> {
|
||||
await this.preferences.put(key, value);
|
||||
await this.preferences.flush();
|
||||
public setKv(key: string, value: string): void {
|
||||
this.preferences.putSync(key, value);
|
||||
this.preferences.flush();
|
||||
}
|
||||
|
||||
public async getKv(key: string): Promise<string> {
|
||||
return await this.preferences.get(key, '') as string;
|
||||
public getKv(key: string): string {
|
||||
return this.preferences.getSync(key, '') as string;
|
||||
}
|
||||
|
||||
public async isFirstTime(): Promise<boolean> {
|
||||
return await this.preferences.get('firstTime', false) as boolean;
|
||||
public isFirstTime(): boolean {
|
||||
return this.preferences.getSync('firstTime', false) as boolean;
|
||||
}
|
||||
|
||||
public async rolledBackVersion(): Promise<string> {
|
||||
return await this.preferences.get('rolledBackVersion', '') as string;
|
||||
public rolledBackVersion(): string {
|
||||
return this.preferences.getSync('rolledBackVersion', '') 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;
|
||||
public markSuccess(): void {
|
||||
this.preferences.putSync('firstTimeOk', true);
|
||||
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
|
||||
const curVersion = this.preferences.getSync('currentVersion', '') as string;
|
||||
|
||||
if (lastVersion && lastVersion !== curVersion) {
|
||||
await this.preferences.delete('lastVersion');
|
||||
await this.preferences.delete(`hash_${lastVersion}`);
|
||||
this.preferences.deleteSync('lastVersion');
|
||||
this.preferences.deleteSync(`hash_${lastVersion}`);
|
||||
}
|
||||
await this.preferences.flush();
|
||||
this.preferences.flush();
|
||||
this.cleanUp();
|
||||
}
|
||||
|
||||
@@ -137,29 +140,29 @@ export class UpdateContext {
|
||||
params.unzipDirectory = `${this.rootDir}/${hash}`;
|
||||
|
||||
const downloadTask = new DownloadTask(this.context);
|
||||
await downloadTask.execute(params);
|
||||
return await downloadTask.execute(params);
|
||||
} catch (e) {
|
||||
throw e;
|
||||
console.error('Failed to download APK patch:', e);
|
||||
}
|
||||
}
|
||||
|
||||
public async switchVersion(hash: string): Promise<void> {
|
||||
public switchVersion(hash: string): void {
|
||||
try {
|
||||
const bundlePath = `${this.rootDir}/${hash}/bundle.harmony.js`;
|
||||
if (!fileIo.accessSync(bundlePath)) {
|
||||
throw new Error(`Bundle version ${hash} not found.`);
|
||||
}
|
||||
|
||||
const lastVersion = await this.getKv('currentVersion');
|
||||
await this.setKv('currentVersion', hash);
|
||||
|
||||
const lastVersion = this.getKv('currentVersion');
|
||||
this.setKv('currentVersion', hash);
|
||||
if (lastVersion && lastVersion !== hash) {
|
||||
await this.setKv('lastVersion', lastVersion);
|
||||
this.setKv('lastVersion', lastVersion);
|
||||
}
|
||||
|
||||
await this.setKv('firstTime', 'true');
|
||||
await this.setKv('firstTimeOk', 'false');
|
||||
await this.setKv('rolledBackVersion', null);
|
||||
this.setKv('firstTime', 'true');
|
||||
this.setKv('firstTimeOk', 'false');
|
||||
this.setKv('rolledBackVersion', "");
|
||||
} catch (e) {
|
||||
console.error('Failed to switch version:', e);
|
||||
}
|
||||
@@ -176,7 +179,7 @@ export class UpdateContext {
|
||||
return defaultAssetsUrl;
|
||||
}
|
||||
if (!this.isFirstTime()) {
|
||||
if (!this.preferences.get('firstTimeOk', true)) {
|
||||
if (!this.preferences.getSync('firstTimeOk', true)) {
|
||||
return this.rollBack();
|
||||
}
|
||||
}
|
||||
@@ -211,7 +214,7 @@ export class UpdateContext {
|
||||
}
|
||||
|
||||
public getCurrentVersion() : string {
|
||||
const currentVersion = this.preferences.getSync('currentVersion', '') as string;
|
||||
const currentVersion = this.getKv('currentVersion');
|
||||
return currentVersion;
|
||||
}
|
||||
|
||||
|
@@ -1,8 +1,5 @@
|
||||
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';
|
||||
@@ -59,7 +56,7 @@ export class UpdateModuleImpl {
|
||||
options: { updateUrl: string; hash: string }
|
||||
): Promise<void> {
|
||||
try {
|
||||
await updateContext.downloadPatchFromPackage(options.updateUrl, options.hash, {
|
||||
return await updateContext.downloadPatchFromPackage(options.updateUrl, options.hash, {
|
||||
onDownloadCompleted: (params: DownloadTaskParams) => {
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
7
ios/Expo/ExpoPushyModule.swift
Normal file
7
ios/Expo/ExpoPushyModule.swift
Normal file
@@ -0,0 +1,7 @@
|
||||
import ExpoModulesCore
|
||||
|
||||
public class ExpoPushyModule: Module {
|
||||
public func definition() -> ModuleDefinition {
|
||||
Name("ExpoPushy")
|
||||
}
|
||||
}
|
10
ios/Expo/ExpoPushyReactDelegateHandler.swift
Normal file
10
ios/Expo/ExpoPushyReactDelegateHandler.swift
Normal file
@@ -0,0 +1,10 @@
|
||||
import ExpoModulesCore
|
||||
import react_native_update
|
||||
|
||||
public final class ExpoPushyReactDelegateHandler: ExpoReactDelegateHandler {
|
||||
private weak var reactDelegate: ExpoReactDelegate?
|
||||
|
||||
public override func bundleURL(reactDelegate: ExpoReactDelegate) -> URL? {
|
||||
return RCTPushy.bundleURL()
|
||||
}
|
||||
}
|
@@ -78,6 +78,7 @@ 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
|
||||
@@ -337,6 +338,26 @@ RCT_EXPORT_METHOD(reloadUpdate:(NSDictionary *)options
|
||||
}
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(restartApp:(RCTPromiseResolveBlock)resolve
|
||||
rejecter:(RCTPromiseRejectBlock)reject)
|
||||
{
|
||||
@try {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[self.bridge reload];
|
||||
});
|
||||
#if __has_include("RCTReloadCommand.h")
|
||||
// reload 0.62+
|
||||
RCTReloadCommandSetBundleURL([[self class] bundleURL]);
|
||||
RCTTriggerReloadCommandListeners(@"pushy restartApp");
|
||||
#endif
|
||||
|
||||
resolve(@true);
|
||||
}
|
||||
@catch (NSException *exception) {
|
||||
reject(@"执行报错", exception.reason, nil);
|
||||
}
|
||||
}
|
||||
|
||||
RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
|
||||
rejecter:(RCTPromiseRejectBlock)reject)
|
||||
{
|
||||
|
11
package.json
11
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-native-update",
|
||||
"version": "10.19.5",
|
||||
"version": "10.28.1",
|
||||
"description": "react-native hot update",
|
||||
"main": "src/index",
|
||||
"scripts": {
|
||||
@@ -26,7 +26,7 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/reactnativecn/react-native-pushy.git"
|
||||
"url": "git+https://github.com/reactnativecn/react-native-update.git"
|
||||
},
|
||||
"keywords": [
|
||||
"react-native",
|
||||
@@ -37,13 +37,13 @@
|
||||
"author": "reactnativecn",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
|
||||
"url": "https://github.com/reactnativecn/react-native-update/issues"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-native": ">=0.59.0"
|
||||
},
|
||||
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
|
||||
"homepage": "https://github.com/reactnativecn/react-native-update#readme",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.3",
|
||||
"react-native-url-polyfill": "^2.0.0"
|
||||
@@ -74,6 +74,5 @@
|
||||
"react-native": "0.73",
|
||||
"ts-jest": "^29.2.5",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72"
|
||||
}
|
||||
}
|
||||
|
@@ -4,6 +4,8 @@ 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']
|
||||
@@ -16,23 +18,40 @@ 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-pushy.git', :tag => '#{s.version}' }
|
||||
s.source_files = "ios/**/*.{h,m,mm,swift}"
|
||||
s.source = { :git => 'https://github.com/reactnativecn/react-native-update.git', :tag => '#{s.version}' }
|
||||
s.source_files = Dir.glob("ios/**/*.{h,m,mm,swift}").reject { |f| f.start_with?("ios/Expo/") }
|
||||
s.libraries = 'bz2', 'z'
|
||||
s.vendored_libraries = 'RCTPushy/libRCTPushy.a'
|
||||
s.pod_target_xcconfig = { 'USER_HEADER_SEARCH_PATHS' => '"$(SRCROOT)/../node_modules/react-native-update/ios"' }
|
||||
s.pod_target_xcconfig = {
|
||||
'USER_HEADER_SEARCH_PATHS' => "#{podspec_dir}/ios",
|
||||
"DEFINES_MODULE" => "YES"
|
||||
}
|
||||
s.resource = 'ios/pushy_build_time.txt'
|
||||
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.script_phase = { :name => 'Generate build time', :script => "set -x;date +%s > \"#{podspec_dir}/ios/pushy_build_time.txt\"", :execution_position => :before_compile }
|
||||
|
||||
s.dependency 'React'
|
||||
s.dependency "React-Core"
|
||||
s.dependency 'SSZipArchive'
|
||||
|
||||
project_root = File.expand_path('../../', __dir__)
|
||||
project_package_json = File.join(project_root, 'package.json')
|
||||
is_expo_project = false
|
||||
|
||||
if (File.exist?(project_package_json))
|
||||
package_json = JSON.parse(File.read(project_package_json))
|
||||
has_expo_dependency = package_json['dependencies'] && package_json['dependencies']['expo']
|
||||
has_expo_modules_core = Dir.exist?('node_modules/expo-modules-core')
|
||||
is_expo_project = has_expo_dependency || has_expo_modules_core
|
||||
if is_expo_project
|
||||
s.dependency 'ExpoModulesCore'
|
||||
end
|
||||
end
|
||||
|
||||
s.subspec 'RCTPushy' do |ss|
|
||||
ss.source_files = 'ios/RCTPushy/*.{h,m,mm,swift}'
|
||||
ss.public_header_files = ['ios/RCTPushy/RCTPushy.h']
|
||||
end
|
||||
|
||||
|
||||
s.subspec 'HDiffPatch' do |ss|
|
||||
ss.source_files = ['ios/RCTPushy/HDiffPatch/**/*.{h,m,c}',
|
||||
'android/jni/hpatch.{h,c}',
|
||||
@@ -40,9 +59,15 @@ 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.private_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
|
||||
ss.public_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
|
||||
end
|
||||
|
||||
|
||||
if is_expo_project
|
||||
s.subspec 'Expo' do |ss|
|
||||
ss.source_files = 'ios/Expo/**/*.{h,m,mm,swift}'
|
||||
end
|
||||
end
|
||||
|
||||
if defined?(install_modules_dependencies()) != nil
|
||||
install_modules_dependencies(s);
|
||||
else
|
||||
@@ -55,7 +80,6 @@ Pod::Spec.new do |s|
|
||||
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
|
||||
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
|
||||
}
|
||||
|
||||
s.dependency "React-Codegen"
|
||||
s.dependency "RCT-Folly"
|
||||
s.dependency "RCTRequired"
|
||||
|
@@ -15,6 +15,7 @@ export interface Spec extends TurboModule {
|
||||
getLocalHashInfo(hash: string): Promise<string>;
|
||||
setUuid(uuid: string): Promise<void>;
|
||||
reloadUpdate(options: { hash: string }): Promise<void>;
|
||||
restartApp(): Promise<void>;
|
||||
setNeedUpdate(options: { hash: string }): Promise<void>;
|
||||
markSuccess(): Promise<void>;
|
||||
downloadPatchFromPpk(options: {
|
||||
|
199
src/client.ts
199
src/client.ts
@@ -1,6 +1,19 @@
|
||||
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
|
||||
import { emptyObj, joinUrls, log, noop, promiseAny, testUrls } from './utils';
|
||||
import { EmitterSubscription, Platform } from 'react-native';
|
||||
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 { PermissionsAndroid } from './permissions';
|
||||
import {
|
||||
PushyModule,
|
||||
@@ -13,33 +26,45 @@ import {
|
||||
setLocalHashInfo,
|
||||
isFirstTime,
|
||||
isRolledBack,
|
||||
getCurrentVersionInfo,
|
||||
} from './core';
|
||||
|
||||
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',
|
||||
],
|
||||
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',
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
if (Platform.OS === 'web') {
|
||||
console.warn('react-native-update 不支持 web 端热更,不会执行操作');
|
||||
}
|
||||
assertWeb();
|
||||
|
||||
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: PushyOptions = {
|
||||
appKey: '',
|
||||
server: defaultServer,
|
||||
autoMarkSuccess: true,
|
||||
updateStrategy: __DEV__ ? 'alwaysAlert' : 'alertUpdateAndIgnoreError',
|
||||
checkStrategy: 'both',
|
||||
logger: noop,
|
||||
debug: false,
|
||||
throwError: false,
|
||||
};
|
||||
|
||||
options = defaultClientOptions;
|
||||
clientType: 'Pushy' | 'Cresc' = 'Pushy';
|
||||
lastChecking?: number;
|
||||
lastRespJson?: Promise<any>;
|
||||
|
||||
@@ -50,7 +75,7 @@ export class Pushy {
|
||||
|
||||
static marked = false;
|
||||
static applyingUpdate = false;
|
||||
version = cInfo.pushy;
|
||||
version = cInfo.rnu;
|
||||
loggerPromise = (() => {
|
||||
let resolve: (value?: unknown) => void = () => {};
|
||||
const promise = new Promise(res => {
|
||||
@@ -62,12 +87,14 @@ export class Pushy {
|
||||
};
|
||||
})();
|
||||
|
||||
constructor(options: PushyOptions) {
|
||||
constructor(options: ClientOptions, clientType?: 'Pushy' | 'Cresc') {
|
||||
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({
|
||||
@@ -79,7 +106,7 @@ export class Pushy {
|
||||
}
|
||||
}
|
||||
|
||||
setOptions = (options: Partial<PushyOptions>) => {
|
||||
setOptions = (options: Partial<ClientOptions>) => {
|
||||
for (const [key, value] of Object.entries(options)) {
|
||||
if (value !== undefined) {
|
||||
(this.options as any)[key] = value;
|
||||
@@ -102,6 +129,7 @@ export class Pushy {
|
||||
log(type + ' ' + message);
|
||||
await this.loggerPromise.promise;
|
||||
const { logger = noop, appKey } = this.options;
|
||||
const info = await getCurrentVersionInfo();
|
||||
logger({
|
||||
type,
|
||||
data: {
|
||||
@@ -111,6 +139,7 @@ export class Pushy {
|
||||
packageVersion,
|
||||
buildTime,
|
||||
message,
|
||||
...info,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
@@ -124,15 +153,24 @@ export class Pushy {
|
||||
return `${endpoint}/checkUpdate/${this.options.appKey}`;
|
||||
};
|
||||
static assertHash = (hash: string) => {
|
||||
if (!Pushy.downloadedHash) {
|
||||
if (!this.downloadedHash) {
|
||||
return;
|
||||
}
|
||||
if (hash !== Pushy.downloadedHash) {
|
||||
if (hash !== this.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;
|
||||
@@ -142,10 +180,7 @@ export class Pushy {
|
||||
this.report({ type: 'markSuccess' });
|
||||
};
|
||||
switchVersion = async (hash: string) => {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
'您调用了switchVersion方法,但是当前是开发环境,不会进行任何操作。',
|
||||
);
|
||||
if (!assertDev('switchVersion()')) {
|
||||
return;
|
||||
}
|
||||
if (Pushy.assertHash(hash) && !Pushy.applyingUpdate) {
|
||||
@@ -156,10 +191,7 @@ export class Pushy {
|
||||
};
|
||||
|
||||
switchVersionLater = async (hash: string) => {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
'您调用了switchVersionLater方法,但是当前是开发环境,不会进行任何操作。',
|
||||
);
|
||||
if (!assertDev('switchVersionLater()')) {
|
||||
return;
|
||||
}
|
||||
if (Pushy.assertHash(hash)) {
|
||||
@@ -168,21 +200,17 @@ export class Pushy {
|
||||
}
|
||||
};
|
||||
checkUpdate = async (extra?: Record<string, any>) => {
|
||||
if (__DEV__ && !this.options.debug) {
|
||||
console.info(
|
||||
'您当前处于开发环境且未启用 debug,不会进行热更检查。如需在开发环境中调试热更,请在 client 中设置 debug 为 true',
|
||||
);
|
||||
if (!this.assertDebug()) {
|
||||
return;
|
||||
}
|
||||
if (Platform.OS === 'web') {
|
||||
console.warn('web 端不支持热更新检查');
|
||||
if (!assertWeb()) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
this.options.beforeCheckUpdate &&
|
||||
(await this.options.beforeCheckUpdate()) === false
|
||||
) {
|
||||
log('beforeCheckUpdate 返回 false, 忽略检查');
|
||||
log('beforeCheckUpdate returned false, skipping check');
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
@@ -205,7 +233,12 @@ export class Pushy {
|
||||
// @ts-ignore
|
||||
delete fetchBody.buildTime;
|
||||
}
|
||||
const body = JSON.stringify(fetchBody);
|
||||
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 fetchPayload = {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -218,13 +251,13 @@ export class Pushy {
|
||||
try {
|
||||
this.report({
|
||||
type: 'checking',
|
||||
message: this.options.appKey + ': ' + body,
|
||||
message: this.options.appKey + ': ' + stringifyBody,
|
||||
});
|
||||
resp = await fetch(this.getCheckUrl(), fetchPayload);
|
||||
} catch (e: any) {
|
||||
this.report({
|
||||
type: 'errorChecking',
|
||||
message: 'Can not connect to update server. Trying backup endpoints.',
|
||||
message: `Can not connect to update server: ${e.message}. Trying backup endpoints.`,
|
||||
});
|
||||
const backupEndpoints = await this.getBackupEndpoints();
|
||||
if (backupEndpoints) {
|
||||
@@ -306,7 +339,7 @@ export class Pushy {
|
||||
this.options.beforeDownloadUpdate &&
|
||||
(await this.options.beforeDownloadUpdate(info)) === false
|
||||
) {
|
||||
log('beforeDownloadUpdate 返回 false, 忽略下载');
|
||||
log('beforeDownloadUpdate returned false, skipping download');
|
||||
return;
|
||||
}
|
||||
if (!info.update || !hash) {
|
||||
@@ -323,19 +356,33 @@ export class Pushy {
|
||||
if (Pushy.progressHandlers[hash]) {
|
||||
return;
|
||||
}
|
||||
const patchStartTime = Date.now();
|
||||
if (onDownloadProgress) {
|
||||
Pushy.progressHandlers[hash] = pushyNativeEventEmitter.addListener(
|
||||
'RCTPushyDownloadProgress',
|
||||
progressData => {
|
||||
if (progressData.hash === hash) {
|
||||
onDownloadProgress(progressData);
|
||||
}
|
||||
},
|
||||
);
|
||||
// @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);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
let succeeded = '';
|
||||
this.report({ type: 'downloading' });
|
||||
let lastError: any;
|
||||
let errorMessages: string[] = [];
|
||||
const diffUrl = await testUrls(joinUrls(paths, diff));
|
||||
if (diffUrl) {
|
||||
log('downloading diff');
|
||||
@@ -347,11 +394,13 @@ export class Pushy {
|
||||
});
|
||||
succeeded = 'diff';
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
const errorMessage = `diff error: ${e.message}`;
|
||||
errorMessages.push(errorMessage);
|
||||
lastError = new Error(errorMessage);
|
||||
if (__DEV__) {
|
||||
succeeded = 'diff';
|
||||
} else {
|
||||
log(`diff error: ${e.message}, try pdiff`);
|
||||
log(errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -365,11 +414,13 @@ export class Pushy {
|
||||
});
|
||||
succeeded = 'pdiff';
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
const errorMessage = `pdiff error: ${e.message}`;
|
||||
errorMessages.push(errorMessage);
|
||||
lastError = new Error(errorMessage);
|
||||
if (__DEV__) {
|
||||
succeeded = 'pdiff';
|
||||
} else {
|
||||
log(`pdiff error: ${e.message}, try full patch`);
|
||||
log(errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -383,11 +434,13 @@ export class Pushy {
|
||||
});
|
||||
succeeded = 'full';
|
||||
} catch (e: any) {
|
||||
lastError = e;
|
||||
const errorMessage = `full patch error: ${e.message}`;
|
||||
errorMessages.push(errorMessage);
|
||||
lastError = new Error(errorMessage);
|
||||
if (__DEV__) {
|
||||
succeeded = 'full';
|
||||
} else {
|
||||
log(`full patch error: ${e.message}`);
|
||||
log(errorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -402,15 +455,25 @@ 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: { newVersion: hash, diff: succeeded },
|
||||
data,
|
||||
});
|
||||
}
|
||||
log(`downloaded ${succeeded} hash:`, hash);
|
||||
@@ -484,4 +547,14 @@ export class Pushy {
|
||||
delete Pushy.progressHandlers[progressKey];
|
||||
}
|
||||
};
|
||||
restartApp = async () => {
|
||||
return PushyModule.restartApp();
|
||||
};
|
||||
}
|
||||
|
||||
// for international users
|
||||
export class Cresc extends Pushy {
|
||||
constructor(options: ClientOptions) {
|
||||
super(options, 'Cresc');
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
import { CheckResult, ProgressData } from './type';
|
||||
import { Pushy } from './client';
|
||||
import { Pushy, Cresc } from './client';
|
||||
|
||||
const noop = () => {};
|
||||
const asyncNoop = () => Promise.resolve();
|
||||
@@ -13,14 +13,15 @@ export const defaultContext = {
|
||||
dismissError: noop,
|
||||
downloadUpdate: asyncNoop,
|
||||
downloadAndInstallApk: asyncNoop,
|
||||
restartApp: asyncNoop,
|
||||
getCurrentVersionInfo: () => Promise.resolve({}),
|
||||
parseTestQrCode: () => false,
|
||||
currentHash: '',
|
||||
packageVersion: '',
|
||||
};
|
||||
|
||||
export const PushyContext = createContext<{
|
||||
checkUpdate: () => Promise<void>;
|
||||
export const UpdateContext = createContext<{
|
||||
checkUpdate: () => Promise<void | CheckResult>;
|
||||
switchVersion: () => Promise<void>;
|
||||
switchVersionLater: () => Promise<void>;
|
||||
markSuccess: () => void;
|
||||
@@ -33,12 +34,16 @@ export const PushyContext = createContext<{
|
||||
metaInfo?: string;
|
||||
}>;
|
||||
parseTestQrCode: (code: string) => boolean;
|
||||
restartApp: () => Promise<void>;
|
||||
currentHash: string;
|
||||
packageVersion: string;
|
||||
client?: Pushy;
|
||||
client?: Pushy | Cresc;
|
||||
progress?: ProgressData;
|
||||
updateInfo?: CheckResult;
|
||||
lastError?: Error;
|
||||
}>(defaultContext);
|
||||
|
||||
export const usePushy = () => useContext(PushyContext);
|
||||
export const useUpdate = () => useContext(UpdateContext);
|
||||
|
||||
/** @deprecated Please use `useUpdate` instead */
|
||||
export const usePushy = useUpdate;
|
||||
|
18
src/core.ts
18
src/core.ts
@@ -4,7 +4,9 @@ const {
|
||||
version: v,
|
||||
} = require('react-native/Libraries/Core/ReactNativeVersion');
|
||||
const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
|
||||
const isTurboModuleEnabled = (global as any).__turboModuleProxy != null;
|
||||
const isTurboModuleEnabled =
|
||||
// https://github.com/facebook/react-native/pull/48362
|
||||
(global as any).__turboModuleProxy || (global as any).RN$Bridgeless;
|
||||
|
||||
export const PushyModule =
|
||||
Platform.OS === 'web'
|
||||
@@ -13,8 +15,12 @@ export const PushyModule =
|
||||
? require('./NativePushy').default
|
||||
: NativeModules.Pushy;
|
||||
|
||||
export const UpdateModule = PushyModule;
|
||||
|
||||
if (!PushyModule) {
|
||||
throw new Error('react-native-update 模块无法加载,请对照安装文档检查配置。');
|
||||
throw new Error(
|
||||
'Failed to load react-native-update native module, please try to recompile',
|
||||
);
|
||||
}
|
||||
|
||||
const PushyConstants = isTurboModuleEnabled
|
||||
@@ -31,12 +37,6 @@ 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 = {
|
||||
pushy: require('../package.json').version,
|
||||
rnu: require('../package.json').version,
|
||||
rn: RNVersion,
|
||||
os: Platform.OS + ' ' + Platform.Version,
|
||||
uuid,
|
||||
|
@@ -1,4 +1,4 @@
|
||||
export { Pushy } from './client';
|
||||
export { PushyContext, usePushy } from './context';
|
||||
export { PushyProvider } from './provider';
|
||||
export { PushyModule } from './core';
|
||||
export { Pushy, Cresc } from './client';
|
||||
export { UpdateContext, usePushy, useUpdate } from './context';
|
||||
export { PushyProvider, UpdateProvider } from './provider';
|
||||
export { PushyModule, UpdateModule } from './core';
|
||||
|
@@ -12,22 +12,24 @@ import {
|
||||
Platform,
|
||||
Linking,
|
||||
} from 'react-native';
|
||||
import { Pushy } from './client';
|
||||
import { Pushy, Cresc } from './client';
|
||||
import { currentVersion, packageVersion, getCurrentVersionInfo } from './core';
|
||||
import { CheckResult, ProgressData, PushyTestPayload } from './type';
|
||||
import { PushyContext } from './context';
|
||||
import { CheckResult, ProgressData, UpdateTestPayload } from './type';
|
||||
import { UpdateContext } from './context';
|
||||
import { URL } from 'react-native-url-polyfill';
|
||||
import { isInRollout } from './isInRollout';
|
||||
import { log } from './utils';
|
||||
|
||||
export const PushyProvider = ({
|
||||
export const UpdateProvider = ({
|
||||
client,
|
||||
children,
|
||||
}: {
|
||||
client: Pushy;
|
||||
client: Pushy | Cresc;
|
||||
children: ReactNode;
|
||||
}) => {
|
||||
client = useRef(client).current;
|
||||
const { options } = client;
|
||||
|
||||
const stateListener = useRef<NativeEventSubscription>();
|
||||
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
|
||||
const updateInfoRef = useRef(updateInfo);
|
||||
@@ -98,6 +100,14 @@ export const PushyProvider = ({
|
||||
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;
|
||||
@@ -129,13 +139,7 @@ export const PushyProvider = ({
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[
|
||||
client,
|
||||
options.updateStrategy,
|
||||
alertUpdate,
|
||||
alertError,
|
||||
throwErrorIfEnabled,
|
||||
],
|
||||
[client, options, alertUpdate, alertError, throwErrorIfEnabled],
|
||||
);
|
||||
|
||||
const downloadAndInstallApk = useCallback(
|
||||
@@ -179,14 +183,14 @@ export const PushyProvider = ({
|
||||
setUpdateInfo(info);
|
||||
if (info.expired) {
|
||||
const { downloadUrl } = info;
|
||||
if (downloadUrl) {
|
||||
if (downloadUrl && Pushy.apkStatus === null) {
|
||||
if (options.updateStrategy === 'silentAndNow') {
|
||||
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
|
||||
downloadAndInstallApk(downloadUrl);
|
||||
} else {
|
||||
Linking.openURL(downloadUrl);
|
||||
}
|
||||
return;
|
||||
return info;
|
||||
}
|
||||
alertUpdate('提示', '您的应用版本已更新,点击更新下载安装新版本', [
|
||||
{
|
||||
@@ -207,7 +211,7 @@ export const PushyProvider = ({
|
||||
options.updateStrategy === 'silentAndLater'
|
||||
) {
|
||||
downloadUpdate(info);
|
||||
return;
|
||||
return info;
|
||||
}
|
||||
alertUpdate(
|
||||
'提示',
|
||||
@@ -224,6 +228,7 @@ export const PushyProvider = ({
|
||||
],
|
||||
);
|
||||
}
|
||||
return info;
|
||||
},
|
||||
[
|
||||
client,
|
||||
@@ -239,15 +244,14 @@ export const PushyProvider = ({
|
||||
const markSuccess = client.markSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
if (__DEV__ && !options.debug) {
|
||||
console.info(
|
||||
'您当前处于开发环境且未启用debug,不会进行热更检查。如需在开发环境中调试热更,请在client中设置debug为true',
|
||||
);
|
||||
if (!client.assertDebug()) {
|
||||
return;
|
||||
}
|
||||
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
|
||||
if (autoMarkSuccess) {
|
||||
markSuccess();
|
||||
setTimeout(() => {
|
||||
markSuccess();
|
||||
}, 1000);
|
||||
}
|
||||
if (checkStrategy === 'both' || checkStrategy === 'onAppResume') {
|
||||
stateListener.current = AppState.addEventListener(
|
||||
@@ -272,10 +276,10 @@ export const PushyProvider = ({
|
||||
stateListener.current && stateListener.current.remove();
|
||||
clearTimeout(dismissErrorTimer);
|
||||
};
|
||||
}, [checkUpdate, options, dismissError, markSuccess]);
|
||||
}, [checkUpdate, options, dismissError, markSuccess, client]);
|
||||
|
||||
const parseTestPayload = useCallback(
|
||||
(payload: PushyTestPayload) => {
|
||||
(payload: UpdateTestPayload) => {
|
||||
if (payload && payload.type && payload.type.startsWith('__rnPushy')) {
|
||||
const logger = options.logger || (() => {});
|
||||
options.logger = ({ type, data }) => {
|
||||
@@ -286,8 +290,8 @@ export const PushyProvider = ({
|
||||
checkUpdate({ extra: { toHash: payload.data } }).then(() => {
|
||||
if (updateInfoRef.current && updateInfoRef.current.upToDate) {
|
||||
Alert.alert(
|
||||
'提示',
|
||||
'当前尚未检测到更新版本,如果是首次扫码,请等待服务器端生成补丁包后再试(约10秒)',
|
||||
'Info',
|
||||
'No update found, please wait 10s for the server to generate the patch package',
|
||||
);
|
||||
}
|
||||
options.logger = logger;
|
||||
@@ -301,7 +305,7 @@ export const PushyProvider = ({
|
||||
);
|
||||
|
||||
const parseTestQrCode = useCallback(
|
||||
(code: string | PushyTestPayload) => {
|
||||
(code: string | UpdateTestPayload) => {
|
||||
try {
|
||||
const payload = typeof code === 'string' ? JSON.parse(code) : code;
|
||||
return parseTestPayload(payload);
|
||||
@@ -312,6 +316,10 @@ export const PushyProvider = ({
|
||||
[parseTestPayload],
|
||||
);
|
||||
|
||||
const restartApp = useCallback(async () => {
|
||||
return client.restartApp();
|
||||
}, [client]);
|
||||
|
||||
useEffect(() => {
|
||||
const parseLinking = (url: string | null) => {
|
||||
if (!url) {
|
||||
@@ -326,16 +334,21 @@ export const PushyProvider = ({
|
||||
};
|
||||
|
||||
Linking.getInitialURL().then(parseLinking);
|
||||
const linkingListener = Linking.addEventListener('url', ({ url }) =>
|
||||
parseLinking(url),
|
||||
);
|
||||
const linkingHandler = ({ url }: { url: string }) => {
|
||||
parseLinking(url);
|
||||
};
|
||||
const linkingListener = Linking.addEventListener('url', linkingHandler);
|
||||
return () => {
|
||||
linkingListener.remove();
|
||||
if ('removeEventListener' in Linking) {
|
||||
(Linking as any).removeEventListener('url', linkingHandler);
|
||||
} else {
|
||||
linkingListener.remove();
|
||||
}
|
||||
};
|
||||
}, [parseTestPayload]);
|
||||
|
||||
return (
|
||||
<PushyContext.Provider
|
||||
<UpdateContext.Provider
|
||||
value={{
|
||||
checkUpdate,
|
||||
switchVersion,
|
||||
@@ -352,8 +365,12 @@ export const PushyProvider = ({
|
||||
downloadAndInstallApk,
|
||||
getCurrentVersionInfo,
|
||||
parseTestQrCode,
|
||||
restartApp,
|
||||
}}>
|
||||
{children}
|
||||
</PushyContext.Provider>
|
||||
</UpdateContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
/** @deprecated Please use `UpdateProvider` instead */
|
||||
export const PushyProvider = UpdateProvider;
|
||||
|
14
src/type.ts
14
src/type.ts
@@ -44,7 +44,7 @@ export type EventType =
|
||||
export interface EventData {
|
||||
currentVersion: string;
|
||||
cInfo: {
|
||||
pushy: string;
|
||||
rnu: string;
|
||||
rn: string;
|
||||
os: string;
|
||||
uuid: string;
|
||||
@@ -54,6 +54,9 @@ export interface EventData {
|
||||
message?: string;
|
||||
rolledBackVersion?: string;
|
||||
newVersion?: string;
|
||||
name?: string;
|
||||
description?: string;
|
||||
metaInfo?: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
@@ -65,15 +68,15 @@ export type UpdateEventsLogger = ({
|
||||
data: EventData;
|
||||
}) => void;
|
||||
|
||||
export interface PushyServerConfig {
|
||||
export interface UpdateServerConfig {
|
||||
main: string;
|
||||
backups?: string[];
|
||||
queryUrls?: string[];
|
||||
}
|
||||
|
||||
export interface PushyOptions {
|
||||
export interface ClientOptions {
|
||||
appKey: string;
|
||||
server?: PushyServerConfig;
|
||||
server?: UpdateServerConfig;
|
||||
logger?: UpdateEventsLogger;
|
||||
updateStrategy?:
|
||||
| 'alwaysAlert'
|
||||
@@ -88,9 +91,10 @@ export interface PushyOptions {
|
||||
throwError?: boolean;
|
||||
beforeCheckUpdate?: () => Promise<boolean>;
|
||||
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
|
||||
afterDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export interface PushyTestPayload {
|
||||
export interface UpdateTestPayload {
|
||||
type: '__rnPushyVersionHash' | string | null;
|
||||
data: any;
|
||||
}
|
||||
|
41
src/utils.ts
41
src/utils.ts
@@ -1,7 +1,7 @@
|
||||
import { Platform } from 'react-native';
|
||||
|
||||
export function log(...args: any[]) {
|
||||
console.log('pushy: ', ...args);
|
||||
console.log('react-native-update: ', ...args);
|
||||
}
|
||||
|
||||
export function promiseAny<T>(promises: Promise<T>[]) {
|
||||
@@ -49,16 +49,16 @@ const ping =
|
||||
return url;
|
||||
}
|
||||
log('ping failed', url, status, statusText);
|
||||
return null;
|
||||
throw new Error('Ping failed');
|
||||
})
|
||||
.catch(e => {
|
||||
pingFinished = true;
|
||||
log('ping error', url, e);
|
||||
return null;
|
||||
throw e;
|
||||
}),
|
||||
new Promise(r =>
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(() => {
|
||||
r(null);
|
||||
reject(new Error('Ping timeout'));
|
||||
if (!pingFinished) {
|
||||
log('ping timeout', url);
|
||||
}
|
||||
@@ -77,10 +77,33 @@ export const testUrls = async (urls?: string[]) => {
|
||||
if (!urls?.length) {
|
||||
return null;
|
||||
}
|
||||
const ret = await promiseAny(urls.map(ping));
|
||||
if (ret) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
try {
|
||||
const ret = await promiseAny(urls.map(ping));
|
||||
if (ret) {
|
||||
return ret;
|
||||
}
|
||||
} catch {}
|
||||
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;
|
||||
};
|
||||
|
Reference in New Issue
Block a user