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

Compare commits

..

67 Commits

Author SHA1 Message Date
sunnylqm
84b71e33a8 support expo 54 2025-10-21 22:23:49 +08:00
sunnylqm
6cd99dece0 Increment version in package.json to 10.34.5, remove obsolete ImportReact.h file, and update podspec to eliminate unnecessary public header files for Expo dependency. 2025-10-21 11:57:09 +08:00
sunnylqm
d726f3602b Update app.json to include package name, modify index.js to use expo-router, and upgrade dependencies in package.json for improved compatibility and features. 2025-10-19 17:40:18 +08:00
sunnylqm
da21c99bcc Update react-native-update dependency to version 10.34.4 in package.json, bun.lock, and Podfile.lock. Add additional flags for Folly configuration in Xcode project settings. 2025-10-18 23:18:23 +08:00
sunnylqm
1f8748375c Enhance Pushy class to support locale configuration in i18n initialization by adding optional locale property to ClientOptions interface. 2025-10-17 16:03:54 +08:00
sunnylqm
fa731cd583 Increment version in package.json to 10.34.4. 2025-10-16 12:56:53 +08:00
sunnylqm
d077dcb6d3 Update submodule references for HDiffPatch and lzma to v3.1.1 commits. 2025-10-16 12:49:59 +08:00
sunnylqm
59b60fdc6d Update .gitmodules to reflect new submodule paths for HDiffPatch and lzma, and increment version in package.json to 10.34.3. 2025-10-16 11:35:39 +08:00
sunnylqm
c768705221 Update .gitmodules to add new submodules for HDiffPatch and lzma, and increment version in package.json to 10.34.2. 2025-10-16 11:13:22 +08:00
sunnylqm
57206dd2f1 Update .gitignore to exclude new harmony package files, remove submodule entries from .gitmodules, and increment version in package.json to 10.34.1. Refactor build-profile.json5 for consistency and update PushyFileJSBundleProvider to handle optional chaining. Remove obsolete pushy.har file and adjust dependencies in oh-package.json5 for clarity. 2025-10-16 00:48:17 +08:00
sunnylqm
4e27d906c3 Reorder properties in CheckResult object for consistency in UpdateProvider component. 2025-09-28 23:23:16 +08:00
sunnylqm
c24f469475 Refactor Pushy class to replace getCurrentVersionInfo with currentVersionInfo for improved clarity and consistency. 2025-09-28 21:57:56 +08:00
sunnylqm
8f8a29eda8 Update version in package.json from 10.34.0-beta.0 to 10.34.0 for stable release. 2025-09-24 16:56:28 +08:00
sunnylqm
a78542b214 Update version to 10.34.0-beta.0 in package.json and modify NDK version for build-lib script; update package manager to yarn@1.22.21. 2025-09-24 15:29:57 +08:00
Sunny Luo
8d9ae57a5f Bump version from 10.32.1 to 10.33.0 2025-09-24 08:28:11 +08:00
Sunny Luo
2502935fc0 Update package.json 2025-09-24 08:27:57 +08:00
波仔糕
8e6d9bf460 update judge logic for v2 (#513)
* update judge logic for v2

* udpate
2025-09-24 08:26:16 +08:00
波仔糕
897f334343 resolve aab package image hot update issue (#512)
* modify harmony download logic to async

* fix harmony image assets load fail issue

* resolve aab package image hot update issue

* update

* udpate
2025-09-23 23:41:40 +08:00
sunnylqm
33bc69c3fb Update react-native-update version to 10.32.0 in package.json for the latest features and improvements. 2025-09-20 12:08:03 +08:00
sunnylqm
5028ce31be Update react-native-update to version 10.32.0 in package.json, refactor error handling in DownloadTask and UpdateContext for improved readability, and enhance type definitions in various files for better TypeScript support. 2025-09-20 12:07:53 +08:00
sunnylqm
d3a4007763 Refactor ProGuard rules for React Native classes to improve reflection handling and maintain compatibility with Expo modules. 2025-09-19 16:03:17 +08:00
sunnylqm
a4f3e3cc38 Update react-native-update to version 10.31.2 in bun.lock, package.json, and Podfile.lock for consistency across dependencies. 2025-09-19 14:58:47 +08:00
sunnylqm
9d51128ed3 Update react-native-update to version 10.31.2 in package.json and enhance currentVersionInfo retrieval in RCTPushy.mm for improved data handling. 2025-09-19 14:50:13 +08:00
sunnylqm
eddb072927 Update Podfile.lock to reflect react-native-update version 10.31.1, ensuring consistency with package dependencies. 2025-09-19 14:42:29 +08:00
sunnylqm
4f9417d620 Update react-native-update to version 10.31.1 in package.json and bun.lock for improved stability and features. 2025-09-19 14:41:52 +08:00
sunnylqm
6f2314d3c9 Update version to 10.31.1, enhance iOS Info.plist with camera and photo library usage descriptions, and refactor code for improved readability in index.tsx. Adjust currentVersionInfo retrieval in RCTPushy.mm for better data handling. 2025-09-19 14:31:07 +08:00
sunnylqm
a6e9ece559 bump 10.31.0 2025-09-17 21:46:28 +08:00
sunnylqm
78430e2ec2 support 0.81 android 2025-09-17 16:36:15 +08:00
sunnylqm
ec5b9e1938 Update dependencies and versioning: bump react-native-update to 10.31.0-beta.3, update form-data and react-native-camera-kit versions, and enhance TypeScript types for better compatibility. 2025-09-17 11:25:51 +08:00
sunnylqm
53dfb45ca2 Update Android build configuration: change React Native architectures and bump version name to 1.81.4 2025-09-17 10:22:04 +08:00
sunnylqm
4a62e89c73 Update gradle-wrapper.jar to the latest version 2025-09-17 10:07:30 +08:00
sunnylqm
655f4c8cf5 update to 0.81.4 2025-09-16 16:56:49 +08:00
sunnylqm
3732c196a1 Implement localized message for disabled incremental hot update in development environment 2025-09-16 12:51:02 +08:00
sunnylqm
bfb520bd07 add currentversioninfo 2025-09-15 23:46:19 +08:00
sunnylqm
f7be8a4d71 Update dependencies in package.json and bun.lock, enhance .gitignore to exclude mcp.json, and refactor provider and utils for improved web support. 2025-09-12 23:28:27 +08:00
sunnylqm
4383a66274 update TypeScript configuration to exclude additional directories: harmony and Example 2025-09-12 00:32:36 +08:00
sunny.ll
a82b75f51f bump version to 10.31.0-beta.1, update TypeScript configuration to include .ts and .tsx files, and initialize stateListener with undefined 2025-09-10 23:07:33 +08:00
sunnylqm
584f698329 bump version to 10.31.0-beta.0 and integrate i18n for improved localization support 2025-09-04 10:24:52 +08:00
sunnylqm
e58903a634 support multiple versions 2025-09-04 00:24:35 +08:00
sunnylqm
41e1028b2d fix first reload 2025-09-03 13:58:57 +08:00
sunnylqm
11d40ce5f2 bump version to 10.30.3 and remove unnecessary code in RCTPushy.mm 2025-09-01 17:03:20 +08:00
sunnylqm
4a1d4d5a50 bump version to 10.30.2 and improve error handling in enhancedFetch function 2025-08-30 11:53:52 +08:00
sunnylqm
02517a9eb0 bump version to 10.30.1 and enhance error handling in enhancedFetch function 2025-08-30 11:14:01 +08:00
sunnylqm
f7309f699f update version to 10.30.0, enhance version and build time tracking in UpdateContext and RCTPushy, and add new entry to .gitignore 2025-08-28 18:45:00 +08:00
sunnylqm
a224113998 bump version to 10.29.9 2025-08-28 14:35:18 +08:00
sunnylqm
f2ede92ea1 add debug resolution for markSuccess method in RCTPushy 2025-08-28 14:33:36 +08:00
sunnylqm
a913e8c10e bump version to 10.29.8 and include new version data in downloading report 2025-08-25 17:18:59 +08:00
sunnylqm
c5f458291a update welcome message in App component and add overridePackageVersion option to ClientOptions 2025-08-22 16:39:33 +08:00
sunnylqm
9699632a43 remove deprecated endpoint from endpoints.json 2025-07-27 10:32:24 +08:00
sunnylqm
80e42f5dba bump version to 10.29.7 and add error handling for hdiffFileAtPath in RCTPushy 2025-07-21 20:57:16 +08:00
sunnylqm
9b718b8f75 support expo 53 2025-06-29 11:52:05 +08:00
sunnylqm
99e3431844 simplify subspec 2025-06-29 00:20:22 +08:00
sunnylqm
d7b5562ab7 improve iOS reload handling 2025-06-28 21:40:06 +08:00
sunnylqm
6a0a5b2d49 fix ios reload 2025-06-27 23:23:59 +08:00
Sunny Luo
7023ff57ca bump 10.29.4 2025-06-25 15:23:08 +08:00
波仔糕
17e21d79cf fix harmony image assets load fail issue (#505)
* modify harmony download logic to async

* fix harmony image assets load fail issue
2025-06-25 15:22:47 +08:00
Sunny Luo
1cab582bd0 Update package.json 2025-06-17 22:29:46 +08:00
波仔糕
7da5a165fd modify harmony download logic to async (#502) 2025-06-17 22:29:28 +08:00
sunnylqm
d5194a1ad1 bump version to 10.29.2 and add delayed execution for clearing first-time and rollback marks in UpdateModule 2025-06-16 12:00:19 +08:00
sunnylqm
ebc9b97e70 fix proguard 2025-06-14 23:34:54 +08:00
sunnylqm
40742e16d8 fix expo reload 2025-06-05 16:04:35 +08:00
sunnylqm
598ae1a506 bump example rn 0.79.2 2025-06-05 14:48:18 +08:00
sunnylqm
e5424591d1 fallback for all 2025-05-21 11:46:40 +08:00
sunnylqm
2cf7336b6a add fallback for android <= 7.0 2025-05-21 11:12:01 +08:00
Sunny Luo
7eac48ab5d 更新 package.json 2025-05-12 14:24:17 +08:00
波仔糕
18d9b75545 update pushy reference method (#499)
* update pushy reference method

* update
2025-05-12 14:23:45 +08:00
sunnylqm
e8ec85c65f cleanup 2025-05-01 20:25:26 +08:00
91 changed files with 4414 additions and 2362 deletions

6
.gitignore vendored
View File

@@ -51,3 +51,9 @@ android/bin
Example/testHotUpdate/harmony
Example/testHotUpdate/android/app/.cxx
Example/harmony_use_pushy/libs
**/mcp.json
harmony/package
**/oh_modules
harmony/pushy/.preview

8
.gitmodules vendored
View File

@@ -4,9 +4,9 @@
[submodule "android/jni/HDiffPatch"]
path = android/jni/HDiffPatch
url = https://github.com/sisong/HDiffPatch.git
[submodule "harmony/src/main/cpp/HDiffPatch"]
path = harmony/src/main/cpp/HDiffPatch
[submodule "harmony/pushy/src/main/cpp/HDiffPatch"]
path = harmony/pushy/src/main/cpp/HDiffPatch
url = https://github.com/sisong/HDiffPatch.git
[submodule "harmony/src/main/cpp/lzma"]
path = harmony/src/main/cpp/lzma
[submodule "harmony/pushy/src/main/cpp/lzma"]
path = harmony/pushy/src/main/cpp/lzma
url = https://github.com/sisong/lzma.git

View File

@@ -20,7 +20,8 @@
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
}
},
"package": "com.anonymous.expoUsePushy"
},
"web": {
"favicon": "./assets/favicon.png"

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1 @@
import { registerRootComponent } from 'expo';
import App from './App';
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
// the environment is set up appropriately
registerRootComponent(App);
import 'expo-router/entry';

View File

@@ -1,24 +1,50 @@
{
"name": "expousepushy",
"version": "1.0.0",
"main": "index.js",
"version": "1.0.0",
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web"
"web": "expo start --web",
"lint": "expo lint"
},
"dependencies": {
"expo": "~52.0.46",
"expo-status-bar": "~2.0.1",
"react": "18.3.1",
"react-native": "0.76.9",
"react-native-update": "^10.28.7"
"@expo/vector-icons": "^14.1.0",
"@react-navigation/bottom-tabs": "^7.3.10",
"@react-navigation/elements": "^2.3.8",
"@react-navigation/native": "^7.1.6",
"expo": "~53.0.22",
"expo-blur": "~14.1.5",
"expo-constants": "~17.1.7",
"expo-font": "~13.3.2",
"expo-haptics": "~14.1.4",
"expo-image": "~2.4.0",
"expo-linking": "~7.1.7",
"expo-router": "~5.1.5",
"expo-splash-screen": "~0.30.10",
"expo-status-bar": "~2.2.3",
"expo-symbols": "~0.4.5",
"expo-system-ui": "~5.0.11",
"expo-web-browser": "~14.2.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"react-native": "0.79.6",
"react-native-gesture-handler": "~2.24.0",
"react-native-reanimated": "~3.17.4",
"react-native-safe-area-context": "5.4.0",
"react-native-screens": "~4.11.1",
"react-native-update": "^10.34.4",
"react-native-web": "~0.20.0",
"react-native-webview": "13.13.5"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@types/react": "~18.3.12",
"typescript": "^5.3.3"
"@types/react": "~19.0.10",
"typescript": "~5.8.3",
"eslint": "^9.25.0",
"eslint-config-expo": "~9.2.0"
},
"private": true
}

View File

@@ -1,45 +1,49 @@
{
"app": {
"signingConfigs": [],
"products": [
app: {
signingConfigs: [],
products: [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS",
"buildOption": {
"strictMode": {
"caseSensitiveCheck": true,
"useNormalizedOHMUrl": true
}
}
}
name: 'default',
signingConfig: 'default',
compatibleSdkVersion: '5.0.0(12)',
runtimeOS: 'HarmonyOS',
buildOption: {
strictMode: {
caseSensitiveCheck: true,
useNormalizedOHMUrl: true,
},
},
},
],
"buildModeSet": [
buildModeSet: [
{
"name": "debug",
name: 'debug',
},
{
"name": "release"
}
]
name: 'release',
},
"modules": [
],
},
modules: [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
name: 'entry',
srcPath: './entry',
targets: [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
name: 'default',
applyToProducts: ['default'],
},
],
},
{
name: 'pushy',
srcPath: '../node_modules/react-native-update/harmony',
}
]
srcPath: '../../../harmony/pushy',
targets: [
{
name: 'default',
applyToProducts: ['default'],
},
],
},
],
}

View File

@@ -1,25 +1,26 @@
{
"meta": {
"stableOrder": true
"stableOrder": true,
"enableUnifiedLockfile": false
},
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
"specifiers": {
"@rnoh/react-native-openharmony@0.72.38": "@rnoh/react-native-openharmony@0.72.38",
"pushy@../../node_modules/react-native-update/harmony": "pushy@../../node_modules/react-native-update/harmony"
"pushy@../../node_modules/react-native-update/harmony/pushy": "pushy@../../node_modules/react-native-update/harmony/pushy"
},
"packages": {
"@rnoh/react-native-openharmony@0.72.38": {
"name": "@rnoh/react-native-openharmony",
"name": "",
"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": {
"pushy@../../node_modules/react-native-update/harmony/pushy": {
"name": "pushy",
"version": "3.1.0-0.0.7",
"resolved": "../../node_modules/react-native-update/harmony",
"resolved": "",
"registryType": "local",
"dependencies": {
"@rnoh/react-native-openharmony": "^0.72.38"

View File

@@ -1,13 +1,12 @@
{
"name": "entry",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "",
"author": "",
"license": "",
"dependencies": {
"@rnoh/react-native-openharmony": "0.72.38",
"pushy": "file:../../node_modules/react-native-update/harmony"
}
name: 'entry',
version: '1.0.0',
description: 'Please describe the basic information.',
main: '',
author: '',
license: '',
dependencies: {
'@rnoh/react-native-openharmony': '0.72.38',
pushy: 'file:../../node_modules/react-native-update/harmony/pushy',
},
}

View File

@@ -1,6 +1,6 @@
import { appTasks } from '@ohos/hvigor-ohos-plugin';
import {appTasks} from '@ohos/hvigor-ohos-plugin';
export default {
system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */
plugins:[] /* Custom plugin to extend the functionality of Hvigor. */
}
system: appTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
plugins: [] /* Custom plugin to extend the functionality of Hvigor. */,
};

View File

@@ -18,7 +18,7 @@
"@react-native-oh/react-native-harmony": "^0.72.59",
"react": "18.2.0",
"react-native": "0.72.5",
"react-native-update": "^10.26.4"
"react-native-update": "latest"
},
"devDependencies": {
"@babel/core": "^7.20.0",

View File

@@ -62,3 +62,7 @@ buck-out/
# Ruby / CocoaPods
/ios/Pods/
/vendor/bundle/
# react-native-update
.update
.pushy

View File

@@ -1,7 +1,5 @@
module.exports = {
arrowParens: 'avoid',
bracketSameLine: true,
bracketSpacing: false,
singleQuote: true,
trailingComma: 'all',
};

View File

@@ -81,7 +81,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
versionName "1.81.4"
}
signingConfigs {
debug {

View File

@@ -5,13 +5,11 @@ 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.ReactNativeApplicationEntryPoint.loadReactNative
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 {
@@ -39,10 +37,6 @@ class MainApplication : Application(), ReactApplication {
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()
}
loadReactNative(this)
}
}

View File

@@ -1,11 +1,11 @@
buildscript {
ext {
buildToolsVersion = "35.0.0"
buildToolsVersion = "36.0.0"
minSdkVersion = 24
compileSdkVersion = 35
targetSdkVersion = 35
compileSdkVersion = 36
targetSdkVersion = 36
ndkVersion = "27.1.12297006"
kotlinVersion = "2.0.21"
kotlinVersion = "2.1.20"
}
repositories {
google()

View File

@@ -25,7 +25,8 @@ android.useAndroidX=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
reactNativeArchitectures=arm64-v8a
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in

View File

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

View File

@@ -114,7 +114,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
@@ -205,7 +205,7 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
@@ -213,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.

View File

@@ -1,3 +1,8 @@
@REM Copyright (c) Meta Platforms, Inc. and affiliates.
@REM
@REM This source code is licensed under the MIT license found in the
@REM LICENSE file in the root directory of this source tree.
@rem
@rem Copyright 2015 the original author or authors.
@rem
@@ -70,11 +75,11 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell

File diff suppressed because it is too large Load Diff

View File

@@ -403,6 +403,8 @@
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = "$(inherited)";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";
@@ -475,6 +477,8 @@
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
OTHER_LDFLAGS = "$(inherited)";
REACT_NATIVE_PATH = "${PODS_ROOT}/../../node_modules/react-native";

View File

@@ -2,12 +2,14 @@
#import "RCTPushy.h"
#import <React/RCTBundleURLProvider.h>
#import <ReactAppDependencyProvider/RCTAppDependencyProvider.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"AwesomeProject";
self.dependencyProvider = [RCTAppDependencyProvider new];
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};

View File

@@ -37,8 +37,14 @@
</dict>
</dict>
</dict>
<key>NSCameraUsageDescription</key>
<string>For taking photos</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>NSPhotoLibraryUsageDescription</key>
<string>For saving photos</string>
<key>RCTNewArchEnabled</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
@@ -53,10 +59,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSCameraUsageDescription</key>
<string>For taking photos</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>For saving photos</string>
</dict>
</plist>

File diff suppressed because it is too large Load Diff

View File

@@ -10,43 +10,42 @@
"test:e2e": "detox test --configuration android.emu.debug",
"lint": "eslint .",
"postinstall": "patch-package",
"apk": "cd android && ./gradlew assembleRelease",
"dev:harmony": "react-native bundle-harmony --dev"
"apk": "cd android && ./gradlew assembleRelease"
},
"dependencies": {
"form-data": "^4.0.2",
"form-data": "^4.0.4",
"patch-package": "^8.0.0",
"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"
"react": "19.1.0",
"react-native": "0.81.4",
"react-native-camera-kit": "^16.1.2",
"react-native-paper": "^5.14.5",
"react-native-safe-area-context": "^5.6.1",
"react-native-svg": "^15.13.0",
"react-native-update": "^10.34.4",
"react-native-vector-icons": "^10.3.0"
},
"devDependencies": {
"@babel/core": "^7.26.0",
"@babel/preset-env": "^7.26.0",
"@babel/runtime": "^7.26.0",
"@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",
"@babel/core": "^7.27.3",
"@babel/preset-env": "^7.27.2",
"@babel/runtime": "^7.27.3",
"@react-native-community/cli": "20.0.0",
"@react-native-community/cli-platform-android": "20.0.0",
"@react-native-community/cli-platform-ios": "20.0.0",
"@react-native/babel-preset": "0.81.4",
"@react-native/eslint-config": "0.81.4",
"@react-native/metro-config": "0.81.4",
"@react-native/typescript-config": "0.81.4",
"@types/react": "^19.1.13",
"@types/react-test-renderer": "^19.1.0",
"detox": "^20.41.2",
"eslint": "^9.35.0",
"jest": "^29.6.3",
"prettier": "2.8.8",
"react-test-renderer": "19.0.0",
"typescript": "5.8.2"
"react-test-renderer": "19.1.1",
"typescript": "5.8.3"
},
"engines": {
"node": ">=18"
"node": ">=20"
},
"trustedDependencies": [
"detox",

View File

@@ -1,6 +1,6 @@
/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */
import React, {useRef, useState} from 'react';
import React, { useRef, useState } from 'react';
import {
StyleSheet,
Platform,
@@ -19,14 +19,14 @@ import {
Modal,
Portal,
} from 'react-native-paper';
import {Camera} from 'react-native-camera-kit';
import {LocalSvg} from 'react-native-svg/css';
import { Camera } from 'react-native-camera-kit';
import { LocalSvg } from 'react-native-svg/css';
import TestConsole from './TestConsole';
import _updateConfig from '../update.json';
import {UpdateProvider, Pushy, Cresc, useUpdate} from 'react-native-update';
const {appKey} = _updateConfig[Platform.OS];
import { UpdateProvider, Pushy, Cresc, useUpdate } from 'react-native-update';
const { appKey } = _updateConfig[Platform.OS];
function App() {
const {
@@ -39,7 +39,8 @@ function App() {
packageVersion,
currentHash,
parseTestQrCode,
progress: {received, total} = {},
progress: { received, total } = {},
currentVersionInfo,
} = useUpdate();
const [useDefaultAlert, setUseDefaultAlert] = useState(true);
const [showTestConsole, setShowTestConsole] = useState(false);
@@ -52,8 +53,8 @@ function App() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>使Pushy热更新服务</Text>
<View style={{flexDirection: 'row'}}>
<Text style={styles.welcome}>22使Pushy热更新服务</Text>
<View style={{ flexDirection: 'row' }}>
<Text>
{useDefaultAlert ? '当前使用' : '当前不使用'}alert更新提示
</Text>
@@ -72,9 +73,9 @@ function App() {
<Portal>
<Modal visible={showCamera} onDismiss={() => setShowCamera(false)}>
<Camera
style={{minHeight: 320}}
style={{ minHeight: 320 }}
scanBarcode={true}
onReadCode={({nativeEvent: {codeStringValue}}) => {
onReadCode={({ nativeEvent: { codeStringValue } }) => {
// 防止重复扫码
if (lastParsedCode.current === codeStringValue) {
return;
@@ -92,7 +93,7 @@ function App() {
/>
</Modal>
</Portal>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 10}}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Text>png:</Text>
<Image
resizeMode={'contain'}
@@ -100,11 +101,11 @@ function App() {
style={styles.image}
/>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', gap: 10}}>
<View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
<Text>svg:</Text>
<LocalSvg
asset={require('./assets/react-logo.svg')}
style={{width: 30, height: 30}}
style={{ width: 30, height: 30 }}
/>
</View>
<Text style={styles.instructions}>
@@ -113,6 +114,7 @@ function App() {
{'\n'}
Hash: {currentHash || '(空)'}
{'\n'}
: {JSON.stringify(currentVersionInfo) || '(空)'}
</Text>
<Text>
{received} / {total}
@@ -121,16 +123,18 @@ function App() {
onPress={() => {
checkUpdate();
setShowUpdateSnackbar(true);
}}>
}}
>
<Text style={styles.instructions}></Text>
</TouchableOpacity>
<TouchableOpacity
testID="testcase"
style={{marginTop: 15}}
style={{ marginTop: 15 }}
onLongPress={() => {
setShowTestConsole(true);
}}>
}}
>
<Text style={styles.instructions}>
react-native-update版本{client?.version}
</Text>
@@ -152,14 +156,15 @@ function App() {
await downloadUpdate();
setShowUpdateBanner(true);
},
}}>
<Text style={{color: 'white'}}>
}}
>
<Text style={{ color: 'white' }}>
({updateInfo.name})
</Text>
</Snackbar>
)}
<Banner
style={{width: '100%', position: 'absolute', top: 0}}
style={{ width: '100%', position: 'absolute', top: 0 }}
visible={showUpdateBanner}
actions={[
{
@@ -174,9 +179,10 @@ function App() {
},
},
]}
icon={({size}) => (
icon={({ size }) => (
<Icon name="checkcircleo" size={size} color="#00f" />
)}>
)}
>
</Banner>
</View>

View File

@@ -0,0 +1,5 @@
{
"extends": "@react-native/typescript-config",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["**/node_modules", "**/Pods"]
}

View File

@@ -1,7 +1,7 @@
{
"ios": {
"appId": 24794,
"appKey": "SqShg4Klnj2hG6LAFMW2PdcgSSuniz0T"
"appId": 28943,
"appKey": "d-OmPxIBivPrDfKhLHjxN-HS"
},
"android": {
"appId": 27509,

View File

@@ -101,7 +101,7 @@ android {
minSdkVersion safeExtGet('minSdkVersion', 16)
targetSdkVersion safeExtGet('targetSdkVersion', 27)
versionCode 1
versionName "1.0"
versionName "1.81.4"
consumerProguardFiles "proguard.pro"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

15
android/proguard.pro vendored
View File

@@ -1,3 +1,18 @@
# Keep our update module classes
-keepnames class cn.reactnative.modules.update.DownloadTask { *; }
-keepnames class cn.reactnative.modules.update.UpdateModuleImpl { *; }
-keepnames class cn.reactnative.modules.update.** { *; }
# Keep React Native classes
-keepnames class com.facebook.react.ReactInstanceManager { *; }
-keepnames class com.facebook.react.** { *; }
-keepnames class com.facebook.react.bridge.** { *; }
-keepnames class com.facebook.react.devsupport.** { *; }
# Keep fields used in reflection
-keepclassmembers class com.facebook.react.ReactActivity { *; }
-keepclassmembers class com.facebook.react.ReactInstanceManager { *; }
-keepclassmembers class com.facebook.react.ReactDelegate { *; }
-keepclassmembers class com.facebook.react.ReactHost { *; }
-keepnames class expo.modules.ExpoReactHostFactory$ExpoReactHostDelegate { *; }

View File

@@ -25,6 +25,7 @@ import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.CRC32;
import java.util.HashMap;
import okio.BufferedSink;
@@ -198,6 +199,10 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
return fout.toByteArray();
}
private String getCRC32AsDecimal(long crc32Value) {
return String.valueOf(crc32Value & 0xFFFFFFFFL);
}
private void copyFilesWithBlacklist(String current, File from, File to, JSONObject blackList) throws IOException {
File[] files = from.listFiles();
for (File file : files) {
@@ -273,12 +278,41 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
zipFile.close();
}
private void copyFromResourceV2(HashMap<String, ArrayList<File>> resToCopy2) throws IOException {
SafeZipFile zipFile = new SafeZipFile(new File(context.getPackageResourcePath()));
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry ze = entries.nextElement();
String fn = ze.getName();
long zipCrc32 = ze.getCrc();
String crc32Decimal = getCRC32AsDecimal(zipCrc32);
ArrayList<File> targets = resToCopy2.get(crc32Decimal);
if (targets != null) {
File lastTarget = null;
for (File target: targets) {
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Copying from resource " + fn + " to " + target);
}
if (lastTarget != null) {
copyFile(lastTarget, target);
} else {
zipFile.unzipToFile(ze, target);
lastTarget = target;
}
}
}
}
zipFile.close();
}
private void doPatchFromApk(DownloadTaskParams param) throws IOException, JSONException {
downloadFile(param);
removeDirectory(param.unzipDirectory);
param.unzipDirectory.mkdirs();
HashMap<String, ArrayList<File>> copyList = new HashMap<String, ArrayList<File>>();
HashMap<String, ArrayList<File>> copiesv2List = new HashMap<String, ArrayList<File>>();
Boolean isV2 = false;
boolean foundDiff = false;
boolean foundBundlePatch = false;
@@ -297,7 +331,35 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
JSONObject obj = (JSONObject)new JSONTokener(json).nextValue();
JSONObject copies = obj.getJSONObject("copies");
JSONObject copiesv2 = obj.getJSONObject("copiesv2");
Iterator<?> keys = copies.keys();
Iterator<?> keysV2 = copiesv2.keys();
if(keysV2.hasNext()){
isV2 = true;
while( keysV2.hasNext() ) {
String from = (String)keysV2.next();
String to = copiesv2.getString(from);
if (from.isEmpty()) {
from = to;
}
ArrayList<File> target = null;
if (!copiesv2List.containsKey(from)) {
target = new ArrayList<File>();
copiesv2List.put(from, target);
} else {
target = copiesv2List.get((from));
}
File toFile = new File(param.unzipDirectory, to);
// Fixing a Zip Path Traversal Vulnerability
// https://support.google.com/faqs/answer/9294009
String canonicalPath = toFile.getCanonicalPath();
if (!canonicalPath.startsWith(param.unzipDirectory.getCanonicalPath() + File.separator)) {
throw new SecurityException("Illegal name: " + to);
}
target.add(toFile);
}
}else{
while( keys.hasNext() ) {
String to = (String)keys.next();
String from = copies.getString(to);
@@ -321,6 +383,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
}
target.add(toFile);
}
}
continue;
}
if (fn.equals("index.bundlejs.patch")) {
@@ -348,7 +411,11 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
throw new Error("bundle patch not found");
}
if(isV2){
copyFromResourceV2(copiesv2List);
}else{
copyFromResource(copyList);
}
if (UpdateContext.DEBUG) {
Log.d("react-native-update", "Unzip finished");

View File

@@ -36,10 +36,28 @@ public class UpdateContext {
this.sp = context.getSharedPreferences("update", Context.MODE_PRIVATE);
String packageVersion = getPackageVersion();
if (!packageVersion.equals(this.sp.getString("packageVersion", null))) {
String buildTime = getBuildTime();
String storedPackageVersion = this.sp.getString("packageVersion", null);
String storedBuildTime = this.sp.getString("buildTime", null);
// If stored versions don't exist, write current versions first
if (storedPackageVersion == null || storedBuildTime == null) {
SharedPreferences.Editor editor = sp.edit();
editor.putString("packageVersion", packageVersion);
editor.putString("buildTime", buildTime);
editor.apply();
storedPackageVersion = packageVersion;
storedBuildTime = buildTime;
}
boolean packageVersionChanged = !packageVersion.equals(storedPackageVersion);
boolean buildTimeChanged = !buildTime.equals(storedBuildTime);
if (packageVersionChanged || buildTimeChanged) {
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.putString("packageVersion", packageVersion);
editor.putString("buildTime", buildTime);
editor.apply();
this.cleanUp();
@@ -169,6 +187,7 @@ public class UpdateContext {
}
public void markSuccess() {
if (!BuildConfig.DEBUG) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("firstTimeOk", true);
String lastVersion = sp.getString("lastVersion", null);
@@ -181,6 +200,7 @@ public class UpdateContext {
this.cleanUp();
}
}
public void clearFirstTime() {
SharedPreferences.Editor editor = sp.edit();

View File

@@ -24,6 +24,38 @@ public class UpdateModuleImpl {
public static final String NAME = "Pushy";
/**
* 获取字段的兼容性方法尝试带m前缀和不带m前缀的字段名
* @param clazz 目标类
* @param fieldName 基础字段名不带m前缀
* @return 找到的字段对象
* @throws NoSuchFieldException 如果两种命名都找不到字段
*/
private static Field getCompatibleField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
// 首先尝试带m前缀的字段名
try {
return clazz.getDeclaredField("m" + capitalize(fieldName));
} catch (NoSuchFieldException e) {
// 如果找不到带m前缀的尝试不带m前缀的
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e2) {
// 如果都找不到,抛出异常并包含两种尝试的信息
throw new NoSuchFieldException("Field not found with either name: m" + capitalize(fieldName) + " or " + fieldName);
}
}
}
/**
* 首字母大写的辅助方法
*/
private static String capitalize(String str) {
if (str == null || str.length() == 0) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
public static void downloadFullUpdate(UpdateContext updateContext, final ReadableMap options, final Promise promise) {
String url = options.getString("updateUrl");
String hash = options.getString("hash");
@@ -143,17 +175,26 @@ public class UpdateModuleImpl {
ReactDelegate reactDelegate = (ReactDelegate)
getReactDelegateMethod.invoke(currentActivity);
Field reactHostField = ReactDelegate.class.getDeclaredField("mReactHost");
Field reactHostField = getCompatibleField(ReactDelegate.class, "reactHost");
reactHostField.setAccessible(true);
Object reactHost = reactHostField.get(reactDelegate);
// Access the mReactHostDelegate field
Field reactHostDelegateField = reactHost.getClass().getDeclaredField("mReactHostDelegate");
Field devSupport = getCompatibleField(reactHost.getClass(), "useDevSupport");
devSupport.setAccessible(true);
devSupport.set(reactHost, false);
// Access the ReactHostDelegate field (compatible with mReactHostDelegate/reactHostDelegate)
Field reactHostDelegateField = getCompatibleField(reactHost.getClass(), "reactHostDelegate");
reactHostDelegateField.setAccessible(true);
Object reactHostDelegate = reactHostDelegateField.get(reactHost);
String bundleFieldName = "jsBundleLoader";
if (reactHostDelegate.getClass().getCanonicalName().equals("expo.modules.ExpoReactHostFactory.ExpoReactHostDelegate")) {
bundleFieldName = "_jsBundleLoader";
}
// Modify the jsBundleLoader field
Field jsBundleLoaderField = reactHostDelegate.getClass().getDeclaredField("jsBundleLoader");
Field jsBundleLoaderField = reactHostDelegate.getClass().getDeclaredField(bundleFieldName);
jsBundleLoaderField.setAccessible(true);
jsBundleLoaderField.set(reactHostDelegate, loader);

View File

@@ -4,6 +4,8 @@ import static androidx.core.content.FileProvider.getUriForFile;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
@@ -17,6 +19,7 @@ import java.util.Map;
public class UpdateModule extends NativePushySpec {
UpdateContext updateContext;
public static ReactApplicationContext mContext;
private final Handler handler = new Handler(Looper.getMainLooper());
public UpdateModule(ReactApplicationContext reactContext, UpdateContext updateContext) {
super(reactContext);
this.updateContext = updateContext;
@@ -32,19 +35,31 @@ public class UpdateModule extends NativePushySpec {
final Map<String, Object> constants = new HashMap<>();
constants.put("downloadRootDir", updateContext.getRootDir());
constants.put("packageVersion", updateContext.getPackageVersion());
constants.put("currentVersion", updateContext.getCurrentVersion());
String currentVersion = updateContext.getCurrentVersion();
constants.put("currentVersion", currentVersion);
constants.put("currentVersionInfo", updateContext.getKv("hash_" + currentVersion));
constants.put("buildTime", updateContext.getBuildTime());
constants.put("isUsingBundleUrl", updateContext.getIsUsingBundleUrl());
boolean isFirstTime = updateContext.isFirstTime();
constants.put("isFirstTime", isFirstTime);
if (isFirstTime) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
updateContext.clearFirstTime();
}
}, 2000);
}
String rolledBackVersion = updateContext.rolledBackVersion();
constants.put("rolledBackVersion", rolledBackVersion);
if (rolledBackVersion != null) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
updateContext.clearRollbackMark();
}
}, 2000);
}
constants.put("uuid", updateContext.getKv("uuid"));
return constants;
}

View File

@@ -20,7 +20,6 @@ import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.JSBundleLoader;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.jakewharton.processphoenix.ProcessPhoenix;
import java.io.File;
import java.lang.reflect.Field;
@@ -49,7 +48,9 @@ public class UpdateModule extends ReactContextBaseJavaModule {
final Map<String, Object> constants = new HashMap<>();
constants.put("downloadRootDir", updateContext.getRootDir());
constants.put("packageVersion", updateContext.getPackageVersion());
constants.put("currentVersion", updateContext.getCurrentVersion());
String currentVersion = updateContext.getCurrentVersion();
constants.put("currentVersion", currentVersion);
constants.put("currentVersionInfo", updateContext.getKv("hash_" + currentVersion));
constants.put("buildTime", updateContext.getBuildTime());
constants.put("isUsingBundleUrl", updateContext.getIsUsingBundleUrl());
boolean isFirstTime = updateContext.isFirstTime();

View File

@@ -1 +1 @@
["https://pushy-koa-qgbgqmcpis.cn-beijing.fcapp.run", "https://p.reactnative.cn/api"]
["https://p.reactnative.cn/api"]

View File

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

View File

@@ -1,6 +1,7 @@
{
"meta": {
"stableOrder": true
"stableOrder": true,
"enableUnifiedLockfile": false
},
"lockfileVersion": 3,
"ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.",
@@ -9,7 +10,7 @@
},
"packages": {
"@rnoh/react-native-openharmony@0.72.38": {
"name": "@rnoh/react-native-openharmony",
"name": "",
"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",

View File

@@ -1,5 +1,5 @@
{
"license": "ISC",
"license": "MIT",
"types": "",
"devDependencies": {},
"name": "pushy",
@@ -8,5 +8,6 @@
"version": "3.1.0-0.0.7",
"dependencies": {
"@rnoh/react-native-openharmony":"^0.72.38"
}
},
"modelVersion": "5.0.0"
}

View File

@@ -73,7 +73,7 @@ static jsi::Value _hostFunction_PushyTurboModule_downloadPatchFromPpk(
const jsi::Value* args,
size_t count)
{
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).call(rt,"downloadPatchFromPpk", args, count));
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).callAsync(rt,"downloadPatchFromPpk", args, count));
}
static jsi::Value _hostFunction_PushyTurboModule_downloadPatchFromPackage(
@@ -82,7 +82,7 @@ static jsi::Value _hostFunction_PushyTurboModule_downloadPatchFromPackage(
const jsi::Value* args,
size_t count)
{
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).call(rt,"downloadPatchFromPackage", args, count));
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).callAsync(rt,"downloadPatchFromPackage", args, count));
}
static jsi::Value _hostFunction_PushyTurboModule_downloadFullUpdate(
@@ -91,7 +91,7 @@ static jsi::Value _hostFunction_PushyTurboModule_downloadFullUpdate(
const jsi::Value* args,
size_t count)
{
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).call(rt,"downloadFullUpdate", args, count));
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).callAsync(rt,"downloadFullUpdate", args, count));
}
static jsi::Value _hostFunction_PushyTurboModule_downloadAndInstallApk(
@@ -100,7 +100,7 @@ static jsi::Value _hostFunction_PushyTurboModule_downloadAndInstallApk(
const jsi::Value* args,
size_t count)
{
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).call(rt,"downloadAndInstallApk", args, count));
return jsi::Value(static_cast<ArkTSTurboModule &> (turboModule).callAsync(rt,"downloadAndInstallApk", args, count));
}

View File

@@ -60,13 +60,13 @@ export class DownloadTask {
const exists = fileIo.accessSync(params.targetFile);
if (exists) {
await fileIo.unlink(params.targetFile);
}else{
} else {
const targetDir = params.targetFile.substring(
0,
params.targetFile.lastIndexOf('/'),
);
const exists = fileIo.accessSync(targetDir);
if(!exists){
if (!exists) {
await fileIo.mkdir(targetDir);
}
}
@@ -83,7 +83,7 @@ export class DownloadTask {
},
});
if (response.responseCode > 299) {
throw new Error(`Server error: ${response.responseCode}`);
throw Error(`Server error: ${response.responseCode}`);
}
const contentLength = parseInt(response.header['content-length'] || '0');
@@ -108,9 +108,10 @@ export class DownloadTask {
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`);
throw Error(
`Download incomplete: expected ${contentLength} bytes but got ${stats.size} bytes`,
);
}
} catch (error) {
console.error('Download failed:', error);
throw error;
@@ -142,7 +143,7 @@ export class DownloadTask {
bytesRead = await fileIo
.read(reader.fd, arrayBuffer)
.catch((err: BusinessError) => {
throw new Error(
throw Error(
`Error reading file: ${err.message}, code: ${err.code}`,
);
});
@@ -154,7 +155,7 @@ export class DownloadTask {
length: bytesRead,
})
.catch((err: BusinessError) => {
throw new Error(
throw Error(
`Error writing file: ${err.message}, code: ${err.code}`,
);
});
@@ -295,16 +296,16 @@ export class DownloadTask {
}
}
if(fn !== '.DS_Store'){
if (fn !== '.DS_Store') {
await zip.decompressFile(fn, params.unzipDirectory);
}
}
if (!foundDiff) {
throw new Error('diff.json not found');
throw Error('diff.json not found');
}
if (!foundBundlePatch) {
throw new Error('bundle patch not found');
throw Error('bundle patch not found');
}
await this.copyFromResource(copyList);
}
@@ -366,12 +367,18 @@ export class DownloadTask {
new Uint8Array(entry.content),
);
const outputFile = `${params.unzipDirectory}/bundle.harmony.js`;
const writer = await fileIo.open(outputFile, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY);
const writer = await fileIo.open(
outputFile,
fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY,
);
const chunkSize = 4096;
let bytesWritten = 0;
const totalLength = patched.byteLength;
while (bytesWritten < totalLength) {
const chunk = patched.slice(bytesWritten, bytesWritten + chunkSize);
const chunk = patched.slice(
bytesWritten,
bytesWritten + chunkSize,
);
await fileIo.write(writer.fd, chunk);
bytesWritten += chunk.byteLength;
}
@@ -387,10 +394,10 @@ export class DownloadTask {
}
if (!foundDiff) {
throw new Error('diff.json not found');
throw Error('diff.json not found');
}
if (!foundBundlePatch) {
throw new Error('bundle patch not found');
throw Error('bundle patch not found');
}
console.info('Patch from PPK completed');
}
@@ -478,7 +485,7 @@ export class DownloadTask {
await this.downloadFile(params);
break;
default:
throw new Error(`Unknown task type: ${params.type}`);
throw Error(`Unknown task type: ${params.type}`);
}
params.listener?.onDownloadCompleted(params);

View File

@@ -12,7 +12,7 @@ export class PushyFileJSBundleProvider extends JSBundleProvider {
this.updateContext = new UpdateContext(context);
}
getURL(): string {
return this.updateContext.getBundleUrl();
return this.updateContext.getBundleUrl()?.substring(1);
}
async getBundle(): Promise<ArrayBuffer> {

View File

@@ -9,50 +9,52 @@ import { UpdateModuleImpl } from './UpdateModuleImpl';
import { UpdateContext } from './UpdateContext';
import { EventHub } from './EventHub';
const TAG = "PushyTurboModule"
const TAG = 'PushyTurboModule';
export class PushyTurboModule extends TurboModule {
mUiCtx: common.UIAbilityContext
context: UpdateContext
mUiCtx: common.UIAbilityContext;
context: UpdateContext;
constructor(protected ctx: TurboModuleContext) {
super(ctx);
logger.debug(TAG, ",PushyTurboModule constructor");
this.mUiCtx = ctx.uiAbilityContext
this.context = new UpdateContext(this.mUiCtx)
EventHub.getInstance().setRNInstance(ctx.rnInstance)
logger.debug(TAG, ',PushyTurboModule constructor');
this.mUiCtx = ctx.uiAbilityContext;
this.context = new UpdateContext(this.mUiCtx);
EventHub.getInstance().setRNInstance(ctx.rnInstance);
}
getConstants(): Object {
logger.debug(TAG, ",call getConstants");
logger.debug(TAG, ',call getConstants');
const context = this.mUiCtx;
const preferencesManager = dataPreferences.getPreferencesSync(context,{ name: 'update' });
const isFirstTime = preferencesManager.getSync("isFirstTime", false) as boolean;
const rolledBackVersion = preferencesManager.getSync("rolledBackVersion", "") as string;
const uuid = preferencesManager.getSync("uuid", "") as string;
const currentVersion = preferencesManager.getSync("currentVersion", "") as string;
const buildTime = preferencesManager.getSync("buildTime", "") as string;
const isFirstTime = preferencesManager.getSync('isFirstTime', false) as boolean;
const rolledBackVersion = preferencesManager.getSync('rolledBackVersion', '') as string;
const uuid = preferencesManager.getSync('uuid', '') as string;
const currentVersion = preferencesManager.getSync('currentVersion', '') as string;
const currentVersionInfo = this.context.getKv(`hash_${currentVersion}`);
const buildTime = preferencesManager.getSync('buildTime', '') as string;
const isUsingBundleUrl = this.context.getIsUsingBundleUrl();
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
let packageVersion = '';
try {
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
packageVersion = bundleInfo?.versionName || "Unknown"
packageVersion = bundleInfo?.versionName || 'Unknown';
} catch (error) {
console.error("Failed to get bundle info:", error);
console.error('Failed to get bundle info:', error);
}
if (isFirstTime) {
preferencesManager.deleteSync("isFirstTime");
preferencesManager.deleteSync('isFirstTime');
}
if (rolledBackVersion) {
preferencesManager.deleteSync("rolledBackVersion");
preferencesManager.deleteSync('rolledBackVersion');
}
return {
downloadRootDir: `${context.filesDir}/_update`,
currentVersionInfo,
packageVersion,
currentVersion,
buildTime,
@@ -60,64 +62,64 @@ getConstants(): Object {
isFirstTime,
rolledBackVersion,
uuid,
}
};
}
async setLocalHashInfo(hash: string, info: string): Promise<boolean> {
logger.debug(TAG, ",call setLocalHashInfo");
return UpdateModuleImpl.setLocalHashInfo(this.context,hash,info);
setLocalHashInfo(hash: string, info: string): boolean {
logger.debug(TAG, ',call setLocalHashInfo');
return UpdateModuleImpl.setLocalHashInfo(this.context, hash, info);
}
async getLocalHashInfo(hash: string): Promise<string> {
return UpdateModuleImpl.getLocalHashInfo(this.context,hash);
getLocalHashInfo(hash: string): string {
return UpdateModuleImpl.getLocalHashInfo(this.context, hash);
}
async setUuid(uuid: string): Promise<boolean> {
logger.debug(TAG, `,call setUuid`);
logger.debug(TAG, ',call setUuid');
return UpdateModuleImpl.setUuid(this.context,uuid);
}
async reloadUpdate(options: { hash: string }): Promise<void> {
logger.debug(TAG, `,call reloadUpdate`);
logger.debug(TAG, ',call reloadUpdate');
return UpdateModuleImpl.reloadUpdate(this.context, this.mUiCtx, options);
}
async setNeedUpdate(options: { hash: string }): Promise<boolean> {
logger.debug(TAG, `,call setNeedUpdate`);
logger.debug(TAG, ',call setNeedUpdate');
return UpdateModuleImpl.setNeedUpdate(this.context, options);
}
async markSuccess(): Promise<boolean> {
logger.debug(TAG, `,call markSuccess`);
logger.debug(TAG, ',call markSuccess');
return UpdateModuleImpl.markSuccess(this.context);
}
async downloadPatchFromPpk(options: { updateUrl: string; hash: string; originHash: string }): Promise<void> {
logger.debug(TAG, `,call downloadPatchFromPpk`);
logger.debug(TAG, ',call downloadPatchFromPpk');
return UpdateModuleImpl.downloadPatchFromPpk(this.context, options);
}
async downloadPatchFromPackage(options: { updateUrl: string; hash: string }): Promise<void> {
logger.debug(TAG, `,call downloadPatchFromPackage`);
logger.debug(TAG, ',call downloadPatchFromPackage');
return UpdateModuleImpl.downloadPatchFromPackage(this.context, options);
}
async downloadFullUpdate(options: { updateUrl: string; hash: string }): Promise<void> {
logger.debug(TAG, `,call downloadFullUpdate`);
logger.debug(TAG, ',call downloadFullUpdate');
return UpdateModuleImpl.downloadFullUpdate(this.context, options);
}
async downloadAndInstallApk(options: { url: string; target: string; hash: string }): Promise<void> {
logger.debug(TAG, `,call downloadAndInstallApk`);
logger.debug(TAG, ',call downloadAndInstallApk');
return UpdateModuleImpl.downloadAndInstallApk(this.mUiCtx, options);
}
addListener(eventName: string): void {
logger.debug(TAG, `,call addListener`);
logger.debug(TAG, ',call addListener');
}
removeListeners(count: number): void {
logger.debug(TAG, `,call removeListeners`);
logger.debug(TAG, ',call removeListeners');
}
}

View File

@@ -0,0 +1,281 @@
import preferences from '@ohos.data.preferences';
import bundleManager from '@ohos.bundle.bundleManager';
import fileIo from '@ohos.file.fs';
import { DownloadTask } from './DownloadTask';
import common from '@ohos.app.ability.common';
import { DownloadTaskParams } from './DownloadTaskParams';
export class UpdateContext {
private context: common.UIAbilityContext;
private rootDir: string;
private preferences: preferences.Preferences;
private static DEBUG: boolean = false;
private static isUsingBundleUrl: boolean = false;
constructor(context: common.UIAbilityContext) {
this.context = context;
this.rootDir = context.filesDir + '/_update';
try {
if (!fileIo.accessSync(this.rootDir)) {
fileIo.mkdirSync(this.rootDir);
}
} catch (e) {
console.error('Failed to create root directory:', e);
}
this.initPreferences();
}
private initPreferences() {
try {
this.preferences = preferences.getPreferencesSync(this.context, {
name: 'update',
});
const packageVersion = this.getPackageVersion();
const storedVersion = this.preferences.getSync('packageVersion', '');
if (!storedVersion) {
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
} else if (storedVersion && packageVersion !== storedVersion) {
this.preferences.clear();
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
this.cleanUp();
}
} catch (e) {
console.error('Failed to init preferences:', e);
}
}
public setKv(key: string, value: string): void {
this.preferences.putSync(key, value);
this.preferences.flush();
}
public getKv(key: string): string {
return this.preferences.getSync(key, '') as string;
}
public isFirstTime(): boolean {
return this.preferences.getSync('firstTime', false) as boolean;
}
public rolledBackVersion(): string {
return this.preferences.getSync('rolledBackVersion', '') as string;
}
public markSuccess(): void {
this.preferences.putSync('firstTimeOk', true);
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
const curVersion = this.preferences.getSync('currentVersion', '') as string;
if (lastVersion && lastVersion !== curVersion) {
this.preferences.deleteSync('lastVersion');
this.preferences.deleteSync(`hash_${lastVersion}`);
}
this.preferences.flush();
this.cleanUp();
}
public clearFirstTime(): void {
this.preferences.putSync('firstTime', false);
this.preferences.flush();
this.cleanUp();
}
public clearRollbackMark(): void {
this.preferences.putSync('rolledBackVersion', null);
this.preferences.flush();
this.cleanUp();
}
public async downloadFullUpdate(
url: string,
hash: string,
listener: DownloadFileListener,
): Promise<void> {
try {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FULL;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${hash}.ppk`;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
} catch (e) {
console.error('Failed to download full update:', e);
}
}
public async downloadFile(
url: string,
hash: string,
fileName: string,
listener: DownloadFileListener,
): Promise<void> {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = this.rootDir + '/' + fileName;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
}
public async downloadPatchFromPpk(
url: string,
hash: string,
originHash: string,
listener: DownloadFileListener,
): Promise<void> {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK;
params.url = url;
params.hash = hash;
params.originHash = originHash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${originHash}_${hash}.ppk.patch`;
params.unzipDirectory = `${this.rootDir}/${hash}`;
params.originDirectory = `${this.rootDir}/${params.originHash}`;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
}
public async downloadPatchFromPackage(
url: string,
hash: string,
listener: DownloadFileListener,
): Promise<void> {
try {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FROM_APP;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${hash}.app.patch`;
params.unzipDirectory = `${this.rootDir}/${hash}`;
const downloadTask = new DownloadTask(this.context);
return await downloadTask.execute(params);
} catch (e) {
throw e;
console.error('Failed to download APK patch:', e);
}
}
public switchVersion(hash: string): void {
try {
const bundlePath = `${this.rootDir}/${hash}/bundle.harmony.js`;
if (!fileIo.accessSync(bundlePath)) {
throw Error(`Bundle version ${hash} not found.`);
}
const lastVersion = this.getKv('currentVersion');
this.setKv('currentVersion', hash);
if (lastVersion && lastVersion !== hash) {
this.setKv('lastVersion', lastVersion);
}
this.setKv('firstTime', 'true');
this.setKv('firstTimeOk', 'false');
this.setKv('rolledBackVersion', '');
} catch (e) {
console.error('Failed to switch version:', e);
}
}
public static getBundleUrl(
context: common.UIAbilityContext,
defaultAssetsUrl?: string,
): string {
return new UpdateContext(context).getBundleUrl(defaultAssetsUrl);
}
public getBundleUrl(defaultAssetsUrl?: string): string {
UpdateContext.isUsingBundleUrl = true;
const currentVersion = this.getCurrentVersion();
if (!currentVersion) {
return defaultAssetsUrl;
}
if (!this.isFirstTime()) {
if (!this.preferences.getSync('firstTimeOk', true)) {
return this.rollBack();
}
}
let version = currentVersion;
while (version) {
const bundleFile = `${this.rootDir}/${version}/bundle.harmony.js`;
try {
if (!fileIo.accessSync(bundleFile)) {
console.error(`Bundle version ${version} not found.`);
version = this.rollBack();
continue;
}
return bundleFile;
} catch (e) {
console.error('Failed to access bundle file:', e);
version = this.rollBack();
}
}
return defaultAssetsUrl;
}
getPackageVersion(): string {
let bundleFlags =
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
let packageVersion = '';
try {
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
packageVersion = bundleInfo?.versionName || 'Unknown';
} catch (error) {
console.error('获取包信息失败:', error);
}
return packageVersion;
}
public getCurrentVersion(): string {
const currentVersion = this.getKv('currentVersion');
return currentVersion;
}
private rollBack(): string {
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
const currentVersion = this.preferences.getSync(
'currentVersion',
'',
) as string;
if (!lastVersion) {
this.preferences.deleteSync('currentVersion');
} else {
this.preferences.putSync('currentVersion', lastVersion);
}
this.preferences.putSync('firstTimeOk', true);
this.preferences.putSync('firstTime', false);
this.preferences.putSync('rolledBackVersion', currentVersion);
this.preferences.flush();
return lastVersion;
}
private cleanUp(): void {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_CLEANUP;
params.hash = this.preferences.getSync('currentVersion', '') as string;
params.originHash = this.preferences.getSync('lastVersion', '') as string;
params.unzipDirectory = this.rootDir;
const downloadTask = new DownloadTask(this.context);
downloadTask.execute(params);
}
public getIsUsingBundleUrl(): boolean {
return UpdateContext.isUsingBundleUrl;
}
}
export interface DownloadFileListener {
onDownloadCompleted(params: DownloadTaskParams): void;
onDownloadFailed(error: Error): void;
}

View File

@@ -4,14 +4,14 @@ import { UpdateContext } from './UpdateContext';
import { DownloadTaskParams } from './DownloadTaskParams';
import logger from './Logger';
const TAG = "UpdateModuleImpl";
const TAG = 'UpdateModuleImpl';
export class UpdateModuleImpl {
static readonly NAME = "Pushy";
static readonly NAME = 'Pushy';
static async downloadFullUpdate(
updateContext: UpdateContext,
options: { updateUrl: string; hash: string }
options: { updateUrl: string; hash: string },
): Promise<void> {
try {
await updateContext.downloadFullUpdate(options.updateUrl, options.hash, {
@@ -20,7 +20,7 @@ export class UpdateModuleImpl {
},
onDownloadFailed: (error: Error) => {
return Promise.reject(error);
}
},
});
} catch (error) {
logger.error(TAG, `downloadFullUpdate failed: ${error}`);
@@ -30,18 +30,18 @@ export class UpdateModuleImpl {
static async downloadAndInstallApk(
context: common.UIAbilityContext,
options: { url: string; hash: string; target: string }
options: { url: string; hash: string; target: string },
): Promise<void> {
try {
const want = {
action: 'action.system.home',
parameters: {
uri: 'appmarket://details'
}
uri: 'appmarket://details',
},
};
if (!context) {
throw new Error('获取context失败');
throw Error('获取context失败');
}
await context.startAbility(want);
@@ -53,17 +53,21 @@ export class UpdateModuleImpl {
static async downloadPatchFromPackage(
updateContext: UpdateContext,
options: { updateUrl: string; hash: string }
options: { updateUrl: string; hash: string },
): Promise<void> {
try {
return await updateContext.downloadPatchFromPackage(options.updateUrl, options.hash, {
return await updateContext.downloadPatchFromPackage(
options.updateUrl,
options.hash,
{
onDownloadCompleted: (params: DownloadTaskParams) => {
return Promise.resolve();
},
onDownloadFailed: (error: Error) => {
return Promise.reject(error);
}
});
},
},
);
} catch (error) {
logger.error(TAG, `downloadPatchFromPackage failed: ${error}`);
throw error;
@@ -72,7 +76,7 @@ export class UpdateModuleImpl {
static async downloadPatchFromPpk(
updateContext: UpdateContext,
options: { updateUrl: string; hash: string; originHash: string }
options: { updateUrl: string; hash: string; originHash: string },
): Promise<void> {
try {
await updateContext.downloadPatchFromPpk(
@@ -85,49 +89,49 @@ export class UpdateModuleImpl {
},
onDownloadFailed: (error: Error) => {
return Promise.reject(error);
}
}
},
},
);
} catch (error) {
logger.error(TAG, `downloadPatchFromPpk failed: ${error}`);
throw new Error(`执行报错: ${error.message}`);
throw Error(`执行报错: ${error.message}`);
}
}
static async reloadUpdate(
updateContext: UpdateContext,
context: common.UIAbilityContext,
options: { hash: string }
options: { hash: string },
): Promise<void> {
const hash = options.hash;
if (!hash) {
throw new Error('hash不能为空');
throw Error('hash不能为空');
}
try {
await updateContext.switchVersion(hash);
const bundleInfo = await bundleManager.getBundleInfoForSelf(
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION,
);
await context.terminateSelf();
const want = {
bundleName: bundleInfo.name,
abilityName: context.abilityInfo?.name
abilityName: context.abilityInfo?.name,
};
await context.startAbility(want);
} catch (error) {
logger.error(TAG, `reloadUpdate failed: ${error}`);
throw new Error(`pushy:switchVersion failed ${error.message}`);
throw Error(`pushy:switchVersion failed ${error.message}`);
}
}
static async setNeedUpdate(
updateContext: UpdateContext,
options: { hash: string }
options: { hash: string },
): Promise<boolean> {
const hash = options.hash;
if (!hash) {
throw new Error('hash不能为空');
throw Error('hash不能为空');
}
try {
@@ -135,7 +139,7 @@ export class UpdateModuleImpl {
return true;
} catch (error) {
logger.error(TAG, `setNeedUpdate failed: ${error}`);
throw new Error(`switchVersionLater failed: ${error.message}`);
throw Error(`switchVersionLater failed: ${error.message}`);
}
}
@@ -145,20 +149,20 @@ export class UpdateModuleImpl {
return true;
} catch (error) {
logger.error(TAG, `markSuccess failed: ${error}`);
throw new Error(`执行报错: ${error.message}`);
throw Error(`执行报错: ${error.message}`);
}
}
static async setUuid(
updateContext: UpdateContext,
uuid: string
uuid: string,
): Promise<boolean> {
try {
await updateContext.setKv('uuid', uuid);
return true;
} catch (error) {
logger.error(TAG, `setUuid failed: ${error}`);
throw new Error(`执行报错: ${error.message}`);
throw Error(`执行报错: ${error.message}`);
}
}
@@ -171,27 +175,17 @@ export class UpdateModuleImpl {
}
}
static async setLocalHashInfo(
static setLocalHashInfo(
updateContext: UpdateContext,
hash: string,
info: string
): Promise<boolean> {
if (!this.checkJson(info)) {
await updateContext.setKv(`hash_${hash}`, info);
throw new Error('校验报错:json字符串格式错误');
}
await updateContext.setKv(`hash_${hash}`, info);
info: string,
): boolean {
updateContext.setKv(`hash_${hash}`, info);
return true;
}
static async getLocalHashInfo(
updateContext: UpdateContext,
hash: string
): Promise<string> {
const value = await updateContext.getKv(`hash_${hash}`);
if (!this.checkJson(value)) {
throw new Error('校验报错:json字符串格式错误');
}
static getLocalHashInfo(updateContext: UpdateContext, hash: string): string {
const value = updateContext.getKv(`hash_${hash}`);
return value;
}
}

View File

@@ -1,254 +0,0 @@
import preferences from '@ohos.data.preferences';
import bundleManager from '@ohos.bundle.bundleManager';
import fileIo from '@ohos.file.fs';
import { DownloadTask } from './DownloadTask';
import common from '@ohos.app.ability.common';
import { DownloadTaskParams } from './DownloadTaskParams';
export class UpdateContext {
private context: common.UIAbilityContext;
private rootDir: string;
private preferences: preferences.Preferences;
private static DEBUG: boolean = false;
private static isUsingBundleUrl: boolean = false;
constructor(context: common.UIAbilityContext) {
this.context = context;
this.rootDir = context.filesDir + '/_update';
try {
if (!fileIo.accessSync(this.rootDir)) {
fileIo.mkdirSync(this.rootDir);
}
} catch (e) {
console.error('Failed to create root directory:', e);
}
this.initPreferences();
}
private initPreferences() {
try {
this.preferences = preferences.getPreferencesSync(this.context, {name:'update'});
const packageVersion = this.getPackageVersion();
const storedVersion = this.preferences.getSync('packageVersion', '');
if(!storedVersion){
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
} else if (storedVersion && packageVersion !== storedVersion) {
this.preferences.clear();
this.preferences.putSync('packageVersion', packageVersion);
this.preferences.flush();
this.cleanUp();
}
} catch (e) {
console.error('Failed to init preferences:', e);
}
}
public setKv(key: string, value: string): void {
this.preferences.putSync(key, value);
this.preferences.flush();
}
public getKv(key: string): string {
return this.preferences.getSync(key, '') as string;
}
public isFirstTime(): boolean {
return this.preferences.getSync('firstTime', false) as boolean;
}
public rolledBackVersion(): string {
return this.preferences.getSync('rolledBackVersion', '') as string;
}
public markSuccess(): void {
this.preferences.putSync('firstTimeOk', true);
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
const curVersion = this.preferences.getSync('currentVersion', '') as string;
if (lastVersion && lastVersion !== curVersion) {
this.preferences.deleteSync('lastVersion');
this.preferences.deleteSync(`hash_${lastVersion}`);
}
this.preferences.flush();
this.cleanUp();
}
public clearFirstTime(): void {
this.preferences.putSync('firstTime', false);
this.preferences.flush();
this.cleanUp();
}
public clearRollbackMark(): void {
this.preferences.putSync('rolledBackVersion', null);
this.preferences.flush();
this.cleanUp();
}
public async downloadFullUpdate(url: string, hash: string, listener: DownloadFileListener): Promise<void> {
try {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FULL;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${hash}.ppk`;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
} catch (e) {
console.error('Failed to download full update:', e);
}
}
public async downloadFile(url: string, hash: string, fileName: string, listener: DownloadFileListener): Promise<void> {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PLAIN_DOWNLOAD;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = this.rootDir + '/' + fileName;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
}
public async downloadPatchFromPpk(url: string, hash: string, originHash: string, listener: DownloadFileListener): Promise<void> {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FROM_PPK;
params.url = url;
params.hash = hash;
params.originHash = originHash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${originHash}_${hash}.ppk.patch`;
params.unzipDirectory = `${this.rootDir}/${hash}`;
params.originDirectory = `${this.rootDir}/${params.originHash}`;
const downloadTask = new DownloadTask(this.context);
await downloadTask.execute(params);
}
public async downloadPatchFromPackage(url: string, hash: string, listener: DownloadFileListener): Promise<void> {
try {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_PATCH_FROM_APP;
params.url = url;
params.hash = hash;
params.listener = listener;
params.targetFile = `${this.rootDir}/${hash}.app.patch`;
params.unzipDirectory = `${this.rootDir}/${hash}`;
const downloadTask = new DownloadTask(this.context);
return await downloadTask.execute(params);
} catch (e) {
throw e;
console.error('Failed to download APK patch:', e);
}
}
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 = this.getKv('currentVersion');
this.setKv('currentVersion', hash);
if (lastVersion && lastVersion !== hash) {
this.setKv('lastVersion', lastVersion);
}
this.setKv('firstTime', 'true');
this.setKv('firstTimeOk', 'false');
this.setKv('rolledBackVersion', "");
} catch (e) {
console.error('Failed to switch version:', e);
}
}
public static getBundleUrl(context: common.UIAbilityContext, defaultAssetsUrl?: string): string {
return new UpdateContext(context).getBundleUrl(defaultAssetsUrl);
}
public getBundleUrl(defaultAssetsUrl?: string): string {
UpdateContext.isUsingBundleUrl = true;
const currentVersion = this.getCurrentVersion();
if (!currentVersion) {
return defaultAssetsUrl;
}
if (!this.isFirstTime()) {
if (!this.preferences.getSync('firstTimeOk', true)) {
return this.rollBack();
}
}
let version = currentVersion;
while (version) {
const bundleFile = `${this.rootDir}/${version}/bundle.harmony.js`;
try {
if (!fileIo.accessSync(bundleFile)) {
console.error(`Bundle version ${version} not found.`);
version = this.rollBack();
continue;
}
return bundleFile;
} catch (e) {
console.error('Failed to access bundle file:', e);
version = this.rollBack();
}
}
return defaultAssetsUrl;
}
getPackageVersion(): string {
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
let packageVersion = '';
try {
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags);
packageVersion = bundleInfo?.versionName || "Unknown";
} catch (error) {
console.error("获取包信息失败:", error);
}
return packageVersion;
}
public getCurrentVersion() : string {
const currentVersion = this.getKv('currentVersion');
return currentVersion;
}
private rollBack(): string {
const lastVersion = this.preferences.getSync('lastVersion', '') as string;
const currentVersion = this.preferences.getSync('currentVersion', '') as string;
if (!lastVersion) {
this.preferences.deleteSync('currentVersion');
} else {
this.preferences.putSync('currentVersion', lastVersion);
}
this.preferences.putSync('firstTimeOk', true);
this.preferences.putSync('firstTime', false);
this.preferences.putSync('rolledBackVersion', currentVersion);
this.preferences.flush();
return lastVersion;
}
private cleanUp(): void {
const params = new DownloadTaskParams();
params.type = DownloadTaskParams.TASK_TYPE_CLEANUP;
params.hash = this.preferences.getSync('currentVersion', '') as string;
params.originHash = this.preferences.getSync('lastVersion', '') as string;
params.unzipDirectory = this.rootDir;
const downloadTask = new DownloadTask(this.context);
downloadTask.execute(params);
}
public getIsUsingBundleUrl(): boolean {
return UpdateContext.isUsingBundleUrl;
}
}
export interface DownloadFileListener {
onDownloadCompleted(params: DownloadTaskParams): void;
onDownloadFailed(error: Error): void;
}

View File

@@ -16,6 +16,7 @@
static NSString *const keyPushyInfo = @"REACTNATIVECN_PUSHY_INFO_KEY";
static NSString *const paramPackageVersion = @"packageVersion";
static NSString *const paramBuildTime = @"buildTime";
static NSString *const paramLastVersion = @"lastVersion";
static NSString *const paramCurrentVersion = @"currentVersion";
static NSString *const paramIsFirstTime = @"isFirstTime";
@@ -70,20 +71,36 @@ RCT_EXPORT_MODULE(RCTPushy);
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
if (pushyInfo) {
// Check for version changes first
NSString *curPackageVersion = [RCTPushy packageVersion];
NSString *packageVersion = [pushyInfo objectForKey:paramPackageVersion];
NSString *curBuildTime = [RCTPushy buildTime];
NSString *storedPackageVersion = [defaults stringForKey:paramPackageVersion];
NSString *storedBuildTime = [defaults stringForKey:paramBuildTime];
BOOL needClearPushyInfo = ![curPackageVersion isEqualToString:packageVersion];
if (needClearPushyInfo) {
// If stored versions don't exist, write current versions first
if (!storedPackageVersion || !storedBuildTime) {
[defaults setObject:curPackageVersion forKey:paramPackageVersion];
[defaults setObject:curBuildTime forKey:paramBuildTime];
storedPackageVersion = curPackageVersion;
storedBuildTime = curBuildTime;
}
BOOL packageVersionChanged = ![curPackageVersion isEqualToString:storedPackageVersion];
BOOL buildTimeChanged = ![curBuildTime isEqualToString:storedBuildTime];
if (packageVersionChanged || buildTimeChanged) {
// Clear all update data and store new versions
[defaults setObject:nil forKey:keyPushyInfo];
[defaults setObject:nil forKey:keyHashInfo];
[defaults setObject:@(YES) forKey:KeyPackageUpdatedMarked];
[defaults setObject:curPackageVersion forKey:paramPackageVersion];
[defaults setObject:curBuildTime forKey:paramBuildTime];
// ...need clear files later
}
else {
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
if (pushyInfo) {
NSString *curVersion = pushyInfo[paramCurrentVersion];
BOOL isFirstTime = [pushyInfo[paramIsFirstTime] boolValue];
@@ -93,8 +110,7 @@ RCT_EXPORT_MODULE(RCTPushy);
BOOL needRollback = (!ignoreRollback && isFirstTime == NO && isFirstLoadOK == NO) || loadVersion.length<=0;
if (needRollback) {
loadVersion = [self rollback];
}
else if (isFirstTime && !ignoreRollback){
} else if (isFirstTime && !ignoreRollback){
// bundleURL may be called many times, ignore rollbacks before process restarted again.
ignoreRollback = true;
@@ -117,7 +133,6 @@ RCT_EXPORT_MODULE(RCTPushy);
}
}
}
}
return [RCTPushy binaryBundleURL];
}
@@ -128,13 +143,11 @@ RCT_EXPORT_MODULE(RCTPushy);
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
NSString *lastVersion = pushyInfo[paramLastVersion];
NSString *curVersion = pushyInfo[paramCurrentVersion];
NSString *curPackageVersion = [RCTPushy packageVersion];
if (lastVersion.length) {
// roll back to last version
[defaults setObject:@{paramCurrentVersion:lastVersion,
paramIsFirstTime:@(NO),
paramIsFirstLoadOk:@(YES),
paramPackageVersion:curPackageVersion}
paramIsFirstLoadOk:@(YES)}
forKey:keyPushyInfo];
}
else {
@@ -163,7 +176,11 @@ RCT_EXPORT_MODULE(RCTPushy);
ret[@"isFirstTime"] = [defaults objectForKey:keyFirstLoadMarked];
ret[@"uuid"] = [defaults objectForKey:keyUuid];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
NSString *currentVersion = [pushyInfo objectForKey:paramCurrentVersion];
ret[@"currentVersion"] = currentVersion;
if (currentVersion != nil) {
ret[@"currentVersionInfo"] = [defaults objectForKey:[keyHashInfo stringByAppendingString:currentVersion]];
}
// clear isFirstTimemarked
if (ret[@"isFirstTime"]) {
@@ -297,12 +314,11 @@ RCT_EXPORT_METHOD(setNeedUpdate:(NSDictionary *)options
newInfo[paramLastVersion] = lastVersion;
newInfo[paramIsFirstTime] = @(YES);
newInfo[paramIsFirstLoadOk] = @(NO);
newInfo[paramPackageVersion] = [RCTPushy packageVersion];
[defaults setObject:newInfo forKey:keyPushyInfo];
resolve(@true);
}else{
} else {
reject(@"执行报错", nil, nil);
}
}
@@ -314,22 +330,22 @@ RCT_EXPORT_METHOD(reloadUpdate:(NSDictionary *)options
@try {
NSString *hash = options[@"hash"];
if (hash.length) {
[self setNeedUpdate:options resolver:resolve rejecter:reject];
// reload in earlier version
// 只在 setNeedUpdate 成功后 resolve
[self setNeedUpdate:options resolver:^(id result) {
dispatch_async(dispatch_get_main_queue(), ^{
[self.bridge setValue:[[self class] bundleURL] forKey:@"bundleURL"];
[self.bridge reload];
});
#if __has_include("RCTReloadCommand.h")
// reload 0.62+
RCTReloadCommandSetBundleURL([[self class] bundleURL]);
RCTTriggerReloadCommandListeners(@"pushy reload");
RCTTriggerReloadCommandListeners(@"pushy reloadUpdate");
#else
[self.bridge reload];
#endif
});
resolve(@true);
}else{
} rejecter:^(NSString *code, NSString *message, NSError *error) {
reject(code, message, error);
}];
} else {
reject(@"执行报错", nil, nil);
}
}
@@ -343,13 +359,14 @@ RCT_EXPORT_METHOD(restartApp:(RCTPromiseResolveBlock)resolve
{
@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");
#else
[self.bridge reload];
#endif
});
resolve(@true);
}
@@ -361,6 +378,9 @@ RCT_EXPORT_METHOD(restartApp:(RCTPromiseResolveBlock)resolve
RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
#if DEBUG
resolve(@true);
#else
@try {
// up package info
@@ -384,6 +404,7 @@ RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
@catch (NSException *exception) {
reject(@"执行报错", nil, nil);
}
#endif
}
@@ -542,7 +563,15 @@ RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
callback([self errorWithMessage:ERROR_HDIFFPATCH]);
}
};
@try {
[_fileManager hdiffFileAtPath:bundlePatch fromOrigin:bundleOrigin toDestination:destination completionHandler:completionHandler];
}
@catch (NSException *exception) {
NSLog(@"Pushy _dopatch error: exception occurred during hdiffFileAtPath: %@, reason: %@",
exception.name, exception.reason);
callback([self errorWithMessage:ERROR_HDIFFPATCH]);
}
}
- (void)patch:(NSString *)hash fromBundle:(NSString *)bundleOrigin source:(NSString *)sourceOrigin callback:(void (^)(NSError *error))callback

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "10.28.9",
"version": "10.34.5",
"description": "react-native hot update",
"main": "src/index",
"scripts": {
@@ -9,7 +9,7 @@
"lint": "eslint \"src/*.@(ts|tsx|js|jsx)\" && tsc --noEmit",
"submodule": "git submodule update --init --recursive",
"test": "echo \"Error: no test specified\" && exit 1",
"build-lib": "bun submodule && $ANDROID_HOME/ndk/20.1.5948944/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib",
"build:so": "bun submodule && $ANDROID_HOME/ndk/28.2.13676358/ndk-build NDK_PROJECT_PATH=android APP_BUILD_SCRIPT=android/jni/Android.mk NDK_APPLICATION_MK=android/jni/Application.mk NDK_LIBS_OUT=android/lib",
"build:ios-debug": "cd Example/testHotUpdate && bun && detox build --configuration ios.sim.debug",
"build:ios-release": "cd Example/testHotUpdate && bun && detox build --configuration ios.sim.release",
"test:ios-debug": "cd Example/testHotUpdate && detox test --configuration ios.sim.debug",

View File

@@ -90,13 +90,6 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/reactnativecn/react-native-update.git', :tag => '#{s.version}' }
# Conditionally set source files
if valid_expo_project
s.source_files = Dir.glob("ios/**/*.{h,m,mm,swift}") # Include Expo files
else
s.source_files = Dir.glob("ios/**/*.{h,m,mm,swift}").reject { |f| f.start_with?("ios/Expo/") } # Exclude Expo files
end
s.libraries = 'bz2', 'z'
s.vendored_libraries = 'RCTPushy/libRCTPushy.a'
s.pod_target_xcconfig = {
@@ -116,18 +109,13 @@ Pod::Spec.new do |s|
end
s.subspec 'RCTPushy' do |ss|
ss.source_files = 'ios/RCTPushy/*.{h,m,mm,swift}'
ss.public_header_files = ['ios/RCTPushy/*.h']
end
s.subspec 'HDiffPatch' do |ss|
ss.source_files = ['ios/RCTPushy/HDiffPatch/**/*.{h,m,c}',
ss.source_files = ['ios/RCTPushy/**/*.{h,m,mm,c}',
'android/jni/hpatch.{h,c}',
'android/jni/HDiffPatch/libHDiffPatch/HPatch/*.{h,c}',
'android/jni/HDiffPatch/file_for_patch.{h,c}',
'android/jni/lzma/C/LzmaDec.{h,c}',
'android/jni/lzma/C/Lzma2Dec.{h,c}']
ss.public_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
ss.public_header_files = ['ios/RCTPushy/**/*.h']
end
# Conditionally add Expo subspec and check ExpoModulesCore version

1
react-native.config.js Normal file
View File

@@ -0,0 +1 @@
module.exports = {};

View File

@@ -10,6 +10,7 @@ export interface Spec extends TurboModule {
buildTime: string;
uuid: string;
isUsingBundleUrl: boolean;
currentVersionInfo: string;
};
setLocalHashInfo(hash: string, info: string): Promise<void>;
getLocalHashInfo(hash: string): Promise<string>;

View File

@@ -1,33 +1,34 @@
import { CheckResult, ClientOptions, ProgressData, EventType } from './type';
import {
assertDev,
DeviceEventEmitter,
EmitterSubscription,
Platform,
} from 'react-native';
import {
PushyModule,
buildTime,
cInfo,
currentVersion,
currentVersionInfo,
isFirstTime,
isRolledBack,
packageVersion,
pushyNativeEventEmitter,
rolledBackVersion,
setLocalHashInfo,
} from './core';
import { PermissionsAndroid } from './permissions';
import { CheckResult, ClientOptions, EventType, ProgressData } from './type';
import {
assertWeb,
emptyObj,
enhancedFetch,
joinUrls,
log,
noop,
promiseAny,
testUrls,
} from './utils';
import {
EmitterSubscription,
Platform,
DeviceEventEmitter,
} from 'react-native';
import { PermissionsAndroid } from './permissions';
import {
PushyModule,
buildTime,
cInfo,
pushyNativeEventEmitter,
currentVersion,
packageVersion,
rolledBackVersion,
setLocalHashInfo,
isFirstTime,
isRolledBack,
getCurrentVersionInfo,
} from './core';
import i18n from './i18n';
const SERVER_PRESETS = {
// cn
@@ -91,7 +92,7 @@ export class Pushy {
options = defaultClientOptions;
clientType: 'Pushy' | 'Cresc' = 'Pushy';
lastChecking?: number;
lastRespJson?: Promise<any>;
lastRespJson?: Promise<CheckResult>;
version = cInfo.rnu;
loggerPromise = (() => {
@@ -106,13 +107,17 @@ export class Pushy {
})();
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];
i18n.setLocale(options.locale ?? this.clientType === 'Pushy' ? 'zh' : 'en');
if (Platform.OS === 'ios' || Platform.OS === 'android') {
if (!options.appKey) {
throw Error(i18n.t('error_appkey_required'));
}
}
this.setOptions(options);
if (isRolledBack) {
this.report({
@@ -135,6 +140,16 @@ export class Pushy {
}
};
/**
* Get translated text based on current clientType
* @param key - Translation key
* @param values - Values for interpolation (optional)
* @returns Translated string
*/
t = (key: string, values?: Record<string, string | number>) => {
return i18n.t(key as any, values);
};
report = async ({
type,
message = '',
@@ -147,7 +162,7 @@ export class Pushy {
log(type + ' ' + message);
await this.loggerPromise.promise;
const { logger = noop, appKey } = this.options;
const info = await getCurrentVersionInfo();
const overridePackageVersion = this.options.overridePackageVersion;
logger({
type,
data: {
@@ -155,9 +170,10 @@ export class Pushy {
currentVersion,
cInfo,
packageVersion,
overridePackageVersion,
buildTime,
message,
...info,
...currentVersionInfo,
...data,
},
});
@@ -170,11 +186,9 @@ export class Pushy {
getCheckUrl = (endpoint: string = this.options.server!.main) => {
return `${endpoint}/checkUpdate/${this.options.appKey}`;
};
assertDebug = () => {
assertDebug = (matter: string) => {
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.',
);
console.info(this.t('dev_debug_disabled', { matter }));
return false;
}
return true;
@@ -188,7 +202,7 @@ export class Pushy {
this.report({ type: 'markSuccess' });
};
switchVersion = async (hash: string) => {
if (!assertDev('switchVersion()')) {
if (!this.assertDebug('switchVersion()')) {
return;
}
if (assertHash(hash) && !sharedState.applyingUpdate) {
@@ -199,7 +213,7 @@ export class Pushy {
};
switchVersionLater = async (hash: string) => {
if (!assertDev('switchVersionLater()')) {
if (!this.assertDebug('switchVersionLater()')) {
return;
}
if (assertHash(hash)) {
@@ -208,7 +222,7 @@ export class Pushy {
}
};
checkUpdate = async (extra?: Record<string, any>) => {
if (!this.assertDebug()) {
if (!this.assertDebug('checkUpdate()')) {
return;
}
if (!assertWeb()) {
@@ -231,7 +245,7 @@ export class Pushy {
}
this.lastChecking = now;
const fetchBody = {
packageVersion,
packageVersion: this.options.overridePackageVersion || packageVersion,
hash: currentVersion,
buildTime,
cInfo,
@@ -261,33 +275,47 @@ export class Pushy {
type: 'checking',
message: this.options.appKey + ': ' + stringifyBody,
});
resp = await fetch(this.getCheckUrl(), fetchPayload);
resp = await enhancedFetch(this.getCheckUrl(), fetchPayload);
} catch (e: any) {
this.report({
type: 'errorChecking',
message: `Can not connect to update server: ${e.message}. Trying backup endpoints.`,
message: this.t('error_cannot_connect_backup', { message: e.message }),
});
const backupEndpoints = await this.getBackupEndpoints();
if (backupEndpoints) {
try {
resp = await promiseAny(
backupEndpoints.map(endpoint =>
fetch(this.getCheckUrl(endpoint), fetchPayload),
enhancedFetch(this.getCheckUrl(endpoint), fetchPayload),
),
);
} catch (err: any) {
this.throwIfEnabled(new Error('errorCheckingUseBackup'));
this.throwIfEnabled(Error('errorCheckingUseBackup'));
}
} else {
this.throwIfEnabled(new Error('errorCheckingGetBackup'));
this.throwIfEnabled(Error('errorCheckingGetBackup'));
}
}
if (!resp) {
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Please check your network.',
message: this.t('error_cannot_connect_server'),
});
this.throwIfEnabled(new Error('errorChecking'));
this.throwIfEnabled(Error('errorChecking'));
return this.lastRespJson ? await this.lastRespJson : emptyObj;
}
if (!resp.ok) {
const respText = await resp.text();
const errorMessage = this.t('error_http_status', {
status: resp.status,
statusText: respText,
});
this.report({
type: 'errorChecking',
message: errorMessage,
});
this.throwIfEnabled(Error(errorMessage));
return this.lastRespJson ? await this.lastRespJson : emptyObj;
}
this.lastRespJson = resp.json();
@@ -296,14 +324,6 @@ export class Pushy {
log('checking result:', result);
if (resp.status !== 200) {
this.report({
type: 'errorChecking',
message: result.message,
});
this.throwIfEnabled(new Error(result.message));
}
return result;
};
getBackupEndpoints = async () => {
@@ -389,11 +409,16 @@ export class Pushy {
}
}
let succeeded = '';
this.report({ type: 'downloading' });
this.report({
type: 'downloading',
data: {
newVersion: hash,
},
});
let lastError: any;
let errorMessages: string[] = [];
const diffUrl = await testUrls(joinUrls(paths, diff));
if (diffUrl) {
if (diffUrl && !__DEV__) {
log('downloading diff');
try {
await PushyModule.downloadPatchFromPpk({
@@ -403,18 +428,17 @@ export class Pushy {
});
succeeded = 'diff';
} catch (e: any) {
const errorMessage = `diff error: ${e.message}`;
const errorMessage = this.t('error_diff_failed', {
message: e.message,
});
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
if (__DEV__) {
succeeded = 'diff';
} else {
lastError = Error(errorMessage);
log(errorMessage);
}
}
}
if (!succeeded) {
const pdiffUrl = await testUrls(joinUrls(paths, pdiff));
if (!succeeded && pdiffUrl) {
if (pdiffUrl && !__DEV__) {
log('downloading pdiff');
try {
await PushyModule.downloadPatchFromPackage({
@@ -423,18 +447,18 @@ export class Pushy {
});
succeeded = 'pdiff';
} catch (e: any) {
const errorMessage = `pdiff error: ${e.message}`;
const errorMessage = this.t('error_pdiff_failed', {
message: e.message,
});
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
if (__DEV__) {
succeeded = 'pdiff';
} else {
lastError = Error(errorMessage);
log(errorMessage);
}
}
}
if (!succeeded) {
const fullUrl = await testUrls(joinUrls(paths, full));
if (!succeeded && fullUrl) {
if (fullUrl) {
log('downloading full patch');
try {
await PushyModule.downloadFullUpdate({
@@ -443,23 +467,22 @@ export class Pushy {
});
succeeded = 'full';
} catch (e: any) {
const errorMessage = `full patch error: ${e.message}`;
const errorMessage = this.t('error_full_patch_failed', {
message: e.message,
});
errorMessages.push(errorMessage);
lastError = new Error(errorMessage);
if (__DEV__) {
succeeded = 'full';
} else {
lastError = Error(errorMessage);
log(errorMessage);
}
} else if (__DEV__) {
log(this.t('dev_incremental_update_disabled'));
succeeded = 'full';
}
}
if (sharedState.progressHandlers[hash]) {
sharedState.progressHandlers[hash].remove();
delete sharedState.progressHandlers[hash];
}
if (__DEV__) {
return hash;
}
if (!succeeded) {
this.report({
type: 'errorUpdate',
@@ -506,7 +529,7 @@ export class Pushy {
}
if (sharedState.apkStatus === 'downloaded') {
this.report({ type: 'errorInstallApk' });
this.throwIfEnabled(new Error('errorInstallApk'));
this.throwIfEnabled(Error('errorInstallApk'));
return;
}
if (Platform.Version <= 23) {
@@ -516,7 +539,7 @@ export class Pushy {
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
this.report({ type: 'rejectStoragePermission' });
this.throwIfEnabled(new Error('rejectStoragePermission'));
this.throwIfEnabled(Error('rejectStoragePermission'));
return;
}
} catch (e: any) {
@@ -549,7 +572,7 @@ export class Pushy {
}).catch(() => {
sharedState.apkStatus = null;
this.report({ type: 'errorDownloadAndInstallApk' });
this.throwIfEnabled(new Error('errorDownloadAndInstallApk'));
this.throwIfEnabled(Error('errorDownloadAndInstallApk'));
});
sharedState.apkStatus = 'downloaded';
if (sharedState.progressHandlers[progressKey]) {

View File

@@ -18,6 +18,7 @@ export const defaultContext = {
parseTestQrCode: () => false,
currentHash: '',
packageVersion: '',
currentVersionInfo: {},
};
export const UpdateContext = createContext<{
@@ -28,11 +29,17 @@ export const UpdateContext = createContext<{
dismissError: () => void;
downloadUpdate: () => Promise<boolean | void>;
downloadAndInstallApk: (url: string) => Promise<void>;
// @deprecated use currentVersionInfo instead
getCurrentVersionInfo: () => Promise<{
name?: string;
description?: string;
metaInfo?: string;
}>;
currentVersionInfo: {
name?: string;
description?: string;
metaInfo?: string;
} | null;
parseTestQrCode: (code: string) => boolean;
restartApp: () => Promise<void>;
currentHash: string;

View File

@@ -18,7 +18,7 @@ export const PushyModule =
export const UpdateModule = PushyModule;
if (!PushyModule) {
throw new Error(
throw Error(
'Failed to load react-native-update native module, please try to recompile',
);
}
@@ -30,6 +30,21 @@ const PushyConstants = isTurboModuleEnabled
export const downloadRootDir: string = PushyConstants.downloadRootDir;
export const packageVersion: string = PushyConstants.packageVersion;
export const currentVersion: string = PushyConstants.currentVersion;
const currentVersionInfoString: string = PushyConstants.currentVersionInfo;
let _currentVersionInfo = {};
if (currentVersionInfoString) {
try {
_currentVersionInfo = JSON.parse(currentVersionInfoString);
} catch (error) {
console.error(
'Failed to parse currentVersionInfo:',
currentVersionInfoString,
);
}
}
export const currentVersionInfo = _currentVersionInfo;
export const isFirstTime: boolean = PushyConstants.isFirstTime;
export const rolledBackVersion: string = PushyConstants.rolledBackVersion;
export const isRolledBack: boolean = typeof rolledBackVersion === 'string';
@@ -45,6 +60,7 @@ async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
}
// @deprecated use currentVersionInfo instead
export async function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;

108
src/i18n.ts Normal file
View File

@@ -0,0 +1,108 @@
import zhTranslations from './locales/zh';
import enTranslations from './locales/en';
type TranslationKey = keyof typeof zhTranslations | keyof typeof enTranslations;
type TranslationValues = Record<string, string | number>;
class I18n {
private currentLocale: 'zh' | 'en' = 'en';
private translations = {
zh: zhTranslations,
en: enTranslations,
};
/**
* Set locale directly
* @param locale - 'zh' or 'en'
*/
setLocale(locale: 'zh' | 'en') {
this.currentLocale = locale;
}
/**
* Get current locale
*/
getLocale(): 'zh' | 'en' {
return this.currentLocale;
}
/**
* Translate a key with optional interpolation
* @param key - Translation key
* @param values - Values for interpolation (optional)
* @returns Translated string with interpolated values
*/
t(key: TranslationKey, values?: TranslationValues): string {
const translation =
this.translations[this.currentLocale][
key as keyof (typeof this.translations)[typeof this.currentLocale]
];
if (!translation) {
// Fallback to the other locale if key not found
const fallbackLocale = this.currentLocale === 'zh' ? 'en' : 'zh';
const fallbackTranslation =
this.translations[fallbackLocale][
key as keyof (typeof this.translations)[typeof fallbackLocale]
];
if (!fallbackTranslation) {
// If still not found, return the key itself
return String(key);
}
return this.interpolate(fallbackTranslation, values);
}
return this.interpolate(translation, values);
}
/**
* Interpolate values into a string template
* Supports {{key}} syntax
* @param template - String template with {{key}} placeholders
* @param values - Values to interpolate
* @returns Interpolated string
*/
private interpolate(template: string, values?: TranslationValues): string {
if (!values) {
return template;
}
return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
const value = values[key];
return value !== undefined ? String(value) : match;
});
}
/**
* Add or update translations for a specific locale
* @param locale - Target locale
* @param translations - Translation object to merge
*/
addTranslations(locale: 'zh' | 'en', translations: Record<string, string>) {
this.translations[locale] = {
...this.translations[locale],
...translations,
};
}
}
// Create singleton instance
const i18n = new I18n();
// Export both the instance and the class for flexibility
export { i18n, I18n };
export default i18n;
/**
* Usage examples:
*
* // Direct locale setting (new preferred method)
* i18n.setLocale('zh'); // Chinese
* i18n.setLocale('en'); // English
*
* // Get translations
* i18n.t('checking_update'); // Based on current locale
* i18n.t('download_progress', { progress: 50 }); // With interpolation
*/

74
src/locales/en.ts Normal file
View File

@@ -0,0 +1,74 @@
export default {
// Common messages
checking_update: 'Checking for updates...',
downloading_update: 'Downloading update package...',
installing_update: 'Installing update...',
update_available: 'Update available',
update_downloaded: 'Update downloaded successfully',
update_installed: 'Update installed successfully',
no_update_available: 'You are up to date',
update_failed: 'Update failed',
network_error: 'Network connection error',
download_failed: 'Download failed',
install_failed: 'Installation failed',
// Progress messages with interpolation
download_progress: 'Download progress: {{progress}}%',
download_speed: 'Download speed: {{speed}}/s',
file_size: 'File size: {{size}}',
time_remaining: 'Time remaining: {{time}}',
// Error messages
error_code: 'Error code: {{code}}',
error_message: 'Error message: {{message}}',
retry_count: 'Retry attempt: {{count}}/{{max}}',
// Update info
version_info: 'Version {{version}} ({{build}})',
release_notes: 'Release notes: {{notes}}',
update_size: 'Update size: {{size}}MB',
// Alert messages
alert_title: 'Notice',
alert_update_ready: 'Download completed. Update now?',
alert_next_time: 'Later',
alert_update_now: 'Update Now',
alert_app_updated:
'Your app version has been updated. Click update to download and install the new version',
alert_update_button: 'Update',
alert_cancel: 'Cancel',
alert_confirm: 'OK',
alert_info: 'Info',
alert_no_update_wait:
'No update found, please wait 10s for the server to generate the patch package',
// Error messages
error_appkey_required: 'appKey is required',
error_update_check_failed: 'Update check failed',
error_cannot_connect_server:
'Can not connect to update server. Please check your network.',
error_cannot_connect_backup:
'Can not connect to update server: {{message}}. Trying backup endpoints.',
error_diff_failed: 'diff error: {{message}}',
error_pdiff_failed: 'pdiff error: {{message}}',
error_full_patch_failed: 'full patch error: {{message}}',
error_all_promises_rejected: 'All promises were rejected',
error_ping_failed: 'Ping failed',
error_ping_timeout: 'Ping timeout',
error_http_status: '{{status}} {{statusText}}',
// Development messages
dev_debug_disabled:
'You are currently in the development environment and have not enabled debug mode. {{matter}} will not be performed. If you need to debug {{matter}} in the development environment, please set debug to true in the client.',
dev_log_prefix: 'react-native-update: ',
dev_web_not_supported:
'react-native-update does not support the Web platform and will not perform any operations',
// More alert messages
alert_new_version_found:
'New version {{name}} found. Download now?\n{{description}}',
// Development environment messages
dev_incremental_update_disabled:
'Currently in development environment, incremental hot update cannot be executed and restart will not take effect. If you need to test effective full hot update in development environment (but will reconnect to metro after restart), please enable "ignore timestamp" switch and retry.',
};

71
src/locales/zh.ts Normal file
View File

@@ -0,0 +1,71 @@
export default {
// Common messages
checking_update: '正在检查更新...',
downloading_update: '正在下载更新包...',
installing_update: '正在安装更新...',
update_available: '发现新版本',
update_downloaded: '更新包下载完成',
update_installed: '更新安装完成',
no_update_available: '已是最新版本',
update_failed: '更新失败',
network_error: '网络连接错误',
download_failed: '下载失败',
install_failed: '安装失败',
// Progress messages with interpolation
download_progress: '下载进度: {{progress}}%',
download_speed: '下载速度: {{speed}}/s',
file_size: '文件大小: {{size}}',
time_remaining: '剩余时间: {{time}}',
// Error messages
error_code: '错误代码: {{code}}',
error_message: '错误信息: {{message}}',
retry_count: '重试次数: {{count}}/{{max}}',
// Update info
version_info: '版本 {{version}} ({{build}})',
release_notes: '更新说明: {{notes}}',
update_size: '更新包大小: {{size}}MB',
// Alert messages
alert_title: '提示',
alert_update_ready: '下载完毕,是否立即更新?',
alert_next_time: '下次再说',
alert_update_now: '立即更新',
alert_app_updated: '您的应用版本已更新,点击更新下载安装新版本',
alert_update_button: '更新',
alert_cancel: '取消',
alert_confirm: '确定',
alert_info: '信息',
alert_no_update_wait: '未发现更新请等待10秒让服务器生成补丁包',
// Error messages
error_appkey_required: '需要提供 appKey',
error_update_check_failed: '更新检查失败',
error_cannot_connect_server: '无法连接到更新服务器。请检查网络连接。',
error_cannot_connect_backup:
'无法连接到更新服务器: {{message}}。正在尝试备用端点。',
error_diff_failed: 'diff 错误: {{message}}',
error_pdiff_failed: 'pdiff 错误: {{message}}',
error_full_patch_failed: '完整补丁错误: {{message}}',
error_all_promises_rejected: '所有请求都被拒绝',
error_ping_failed: 'Ping 失败',
error_ping_timeout: 'Ping 超时',
error_http_status: '{{status}} {{statusText}}',
// Development messages
dev_debug_disabled:
'您当前处于开发环境且未启用调试模式。{{matter}} 将不会执行。如需在开发环境中调试 {{matter}},请在客户端中将 debug 设为 true。',
dev_log_prefix: 'react-native-update: ',
dev_web_not_supported:
'react-native-update 不支持 Web 平台,不会执行任何操作',
// More alert messages
alert_new_version_found:
'检查到新的版本{{name}},是否下载?\n{{description}}',
// Development environment messages
dev_incremental_update_disabled:
'当前是开发环境,无法执行增量式热更新,重启不会生效。如果需要在开发环境中测试可生效的全量热更新(但也会在再次重启后重新连接 metro请打开"忽略时间戳"开关再重试。',
};

View File

@@ -13,12 +13,17 @@ import {
Linking,
} from 'react-native';
import { Pushy, Cresc, sharedState } from './client';
import { currentVersion, packageVersion, getCurrentVersionInfo } from './core';
import { CheckResult, ProgressData, UpdateTestPayload } from './type';
import { currentVersion, packageVersion, getCurrentVersionInfo, currentVersionInfo } from './core';
import {
CheckResult,
ProgressData,
UpdateTestPayload,
VersionInfo,
} from './type';
import { UpdateContext } from './context';
import { URL } from 'react-native-url-polyfill';
import { isInRollout } from './isInRollout';
import { log } from './utils';
import { assertWeb, log } from './utils';
export const UpdateProvider = ({
client,
@@ -30,7 +35,7 @@ export const UpdateProvider = ({
client = useRef(client).current;
const { options } = client;
const stateListener = useRef<NativeEventSubscription>();
const stateListener = useRef<NativeEventSubscription>(undefined);
const [updateInfo, setUpdateInfo] = useState<CheckResult>();
const updateInfoRef = useRef(updateInfo);
const [progress, setProgress] = useState<ProgressData>();
@@ -115,16 +120,16 @@ export const UpdateProvider = ({
client.switchVersionLater(hash);
return true;
}
alertUpdate('提示', '下载完毕,是否立即更新?', [
alertUpdate(client.t('alert_title'), client.t('alert_update_ready'), [
{
text: '下次再说',
text: client.t('alert_next_time'),
style: 'cancel',
onPress: () => {
client.switchVersionLater(hash);
},
},
{
text: '立即更新',
text: client.t('alert_update_now'),
style: 'default',
onPress: () => {
client.switchVersion(hash);
@@ -134,7 +139,7 @@ export const UpdateProvider = ({
return true;
} catch (e: any) {
setLastError(e);
alertError('更新失败', e.message);
alertError(client.t('update_failed'), e.message);
throwErrorIfEnabled(e);
return false;
}
@@ -158,25 +163,32 @@ export const UpdateProvider = ({
return;
}
lastChecking.current = now;
let info: CheckResult;
let rootInfo: CheckResult | undefined;
try {
info = await client.checkUpdate(extra);
rootInfo = await client.checkUpdate(extra);
} catch (e: any) {
setLastError(e);
alertError('更新检查失败', e.message);
alertError(client.t('error_update_check_failed'), e.message);
throwErrorIfEnabled(e);
return;
}
if (!info) {
if (!rootInfo) {
return;
}
const versions = [rootInfo.expVersion, rootInfo].filter(Boolean) as VersionInfo[];
delete rootInfo.expVersion;
for (const versionInfo of versions) {
const info: CheckResult = {
...rootInfo,
...versionInfo,
};
const rollout = info.config?.rollout?.[packageVersion];
if (info.update && rollout) {
if (!isInRollout(rollout)) {
log(`not in ${rollout}% rollout, ignored`);
return;
log(`${info.name} not in ${rollout}% rollout, ignored`);
continue;
}
log(`in ${rollout}% rollout, continue`);
log(`${info.name} in ${rollout}% rollout, continue`);
}
info.description = info.description ?? '';
updateInfoRef.current = info;
@@ -199,18 +211,25 @@ export const UpdateProvider = ({
}
return info;
}
alertUpdate('提示', '您的应用版本已更新,点击更新下载安装新版本', [
alertUpdate(
client.t('alert_title'),
client.t('alert_app_updated'),
[
{
text: '更新',
text: client.t('alert_update_button'),
onPress: () => {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
if (
Platform.OS === 'android' &&
downloadUrl.endsWith('.apk')
) {
downloadAndInstallApk(downloadUrl);
} else {
Linking.openURL(downloadUrl);
}
},
},
]);
],
);
}
} else if (info.update) {
if (
@@ -221,12 +240,15 @@ export const UpdateProvider = ({
return info;
}
alertUpdate(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
client.t('alert_title'),
client.t('alert_new_version_found', {
name: info.name!,
description: info.description,
}),
[
{ text: '取消', style: 'cancel' },
{ text: client.t('alert_cancel'), style: 'cancel' },
{
text: '确定',
text: client.t('alert_confirm'),
style: 'default',
onPress: () => {
downloadUpdate();
@@ -236,6 +258,7 @@ export const UpdateProvider = ({
);
}
return info;
}
},
[
client,
@@ -251,7 +274,10 @@ export const UpdateProvider = ({
const markSuccess = client.markSuccess;
useEffect(() => {
if (!client.assertDebug()) {
if (!client.assertDebug('checkUpdate()')) {
return;
}
if (!assertWeb()) {
return;
}
const { checkStrategy, dismissErrorAfter, autoMarkSuccess } = options;
@@ -297,8 +323,8 @@ export const UpdateProvider = ({
checkUpdate({ extra: { toHash: payload.data } }).then(() => {
if (updateInfoRef.current && updateInfoRef.current.upToDate) {
Alert.alert(
'Info',
'No update found, please wait 10s for the server to generate the patch package',
client.t('alert_info'),
client.t('alert_no_update_wait'),
);
}
options.logger = logger;
@@ -308,7 +334,7 @@ export const UpdateProvider = ({
}
return false;
},
[checkUpdate, options],
[checkUpdate, options, client],
);
const parseTestQrCode = useCallback(
@@ -328,6 +354,9 @@ export const UpdateProvider = ({
}, [client]);
useEffect(() => {
if (!assertWeb()) {
return;
}
const parseLinking = (url: string | null) => {
if (!url) {
return;
@@ -371,6 +400,7 @@ export const UpdateProvider = ({
progress,
downloadAndInstallApk,
getCurrentVersionInfo,
currentVersionInfo,
parseTestQrCode,
restartApp,
}}>

View File

@@ -1,14 +1,10 @@
export interface CheckResult {
upToDate?: true;
expired?: true;
downloadUrl?: string;
update?: true;
name?: string; // version name
hash?: string;
description?: string;
metaInfo?: string;
config?: {
rollout?: {
export interface VersionInfo {
name: string;
hash: string;
description: string;
metaInfo: string;
config: {
rollout: {
[packageVersion: string]: number;
};
[key: string]: any;
@@ -16,11 +12,23 @@ export interface CheckResult {
pdiff?: string;
diff?: string;
full?: string;
paths?: string[];
}
interface RootResult {
upToDate?: true;
expired?: true;
downloadUrl?: string;
update?: true;
paused?: 'app' | 'package';
message?: string;
paths?: string[];
}
export type CheckResult = RootResult &
Partial<VersionInfo> & {
expVersion?: VersionInfo;
};
export interface ProgressData {
hash: string;
received: number;
@@ -78,6 +86,7 @@ export interface ClientOptions {
appKey: string;
server?: UpdateServerConfig;
logger?: UpdateEventsLogger;
locale?: 'zh' | 'en';
updateStrategy?:
| 'alwaysAlert'
| 'alertUpdateAndIgnoreError'
@@ -93,6 +102,7 @@ export interface ClientOptions {
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
afterDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
onPackageExpired?: (info: CheckResult) => Promise<boolean>;
overridePackageVersion?: string;
}
export interface UpdateTestPayload {

View File

@@ -1,9 +1,12 @@
import { Platform } from 'react-native';
import i18n from './i18n';
export function log(...args: any[]) {
console.log('react-native-update: ', ...args);
console.log(i18n.t('dev_log_prefix'), ...args);
}
export const isWeb = Platform.OS === 'web';
export function promiseAny<T>(promises: Promise<T>[]) {
return new Promise<T>((resolve, reject) => {
let count = 0;
@@ -14,7 +17,7 @@ export function promiseAny<T>(promises: Promise<T>[]) {
.catch(() => {
count++;
if (count === promises.length) {
reject(new Error('All promises were rejected'));
reject(Error(i18n.t('error_all_promises_rejected')));
}
});
});
@@ -34,22 +37,21 @@ class EmptyModule {
}
export const emptyModule = new EmptyModule();
const ping =
Platform.OS === 'web'
const ping = isWeb
? Promise.resolve
: async (url: string) => {
let pingFinished = false;
return Promise.race([
fetch(url, {
enhancedFetch(url, {
method: 'HEAD',
})
.then(({ status, statusText }) => {
.then(({ status, statusText, url: finalUrl }) => {
pingFinished = true;
if (status === 200) {
return url;
return finalUrl;
}
log('ping failed', url, status, statusText);
throw new Error('Ping failed');
throw Error(i18n.t('error_ping_failed'));
})
.catch(e => {
pingFinished = true;
@@ -58,7 +60,7 @@ const ping =
}),
new Promise((_, reject) =>
setTimeout(() => {
reject(new Error('Ping timeout'));
reject(Error(i18n.t('error_ping_timeout')));
if (!pingFinished) {
log('ping timeout', url);
}
@@ -69,7 +71,7 @@ const ping =
export function joinUrls(paths: string[], fileName?: string) {
if (fileName) {
return paths.map(path => 'https://' + path + '/' + fileName);
return paths.map(path => `https://${path}/${fileName}`);
}
}
@@ -90,21 +92,42 @@ export const testUrls = async (urls?: string[]) => {
};
export const assertWeb = () => {
if (Platform.OS === 'web') {
console.warn(
'react-native-update does not support the Web platform and will not perform any operations',
);
if (isWeb) {
console.warn(i18n.t('dev_web_not_supported'));
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;
// export const isAndroid70AndBelow = () => {
// // android 7.0 and below devices do not support letsencrypt cert
// // https://letsencrypt.org/2023/07/10/cross-sign-expiration/
// return Platform.OS === 'android' && Platform.Version <= 24;
// };
export const enhancedFetch = async (
url: string,
params: Parameters<typeof fetch>[1],
isRetry = false,
): Promise<Response> => {
return fetch(url, params)
.then(r => {
if (r.ok) {
return r;
}
return true;
throw Error(
i18n.t('error_http_status', {
status: r.status,
statusText: r.statusText,
}),
);
})
.catch(e => {
log('fetch error', url, e);
if (isRetry) {
throw e;
}
log('trying fallback to http');
return enhancedFetch(url.replace('https', 'http'), params, true);
});
};

View File

@@ -1,4 +1,5 @@
{
"extends": "@react-native/typescript-config/tsconfig.json",
"include": ["src/**/*"]
"extends": "@react-native/typescript-config",
"include": ["**/*.ts", "**/*.tsx"],
"exclude": ["**/node_modules", "**/Pods", "**/harmony", "**/Example"]
}