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

Compare commits

..

23 Commits

Author SHA1 Message Date
sunnylqm
bf3a0808f6 fix type error 2025-04-11 18:23:38 +08:00
sunnylqm
4a7bb19ca1 do not use static properties 2025-04-11 18:14:57 +08:00
sunnylqm
7a8640d582 fix lint 2025-04-11 17:36:04 +08:00
sunnylqm
ff50e03446 bump 10.28.2 2025-04-11 17:29:44 +08:00
sunnylqm
7888010061 fix asserthash 2025-04-11 17:28:36 +08:00
sunnylqm
a9c360620f add onpackageexpired 2025-04-11 14:48:18 +08:00
sunnylqm
05738ec204 fix android build 2025-04-11 10:17:08 +08:00
sunnylqm
e4ef93595b feat: enhance Pushy logging with version info and update EventData interface 2025-04-10 12:25:16 +08:00
sunnylqm
b336926838 lint error 2025-04-10 12:10:53 +08:00
sunnylqm
628647df98 lint error 2025-04-10 12:08:52 +08:00
sunnylqm
7d76034415 cleanup 2025-04-10 12:05:18 +08:00
Sunny Luo
ac217f659f Update package.json 2025-04-09 11:01:16 +08:00
波仔糕
0e077b1de0 support to Expo (#486)
* support to Expo

* update

* update

* update

---------

Co-authored-by: Steven <steven@Stevens-MacBook-Pro.local>
2025-04-09 10:48:46 +08:00
陈赳赳
1767fe37fa feat: add restartApp (#488) 2025-04-08 16:00:15 +08:00
sunnylqm
7a9f579327 fix ping 2025-04-07 15:05:07 +08:00
sunnylqm
350bfa0c89 delete nvmrc 2025-04-02 14:54:43 +08:00
sunnylqm
58ef3e6b22 cleanup 2025-03-31 12:28:48 +08:00
sunnylqm
4dd89a1e74 fix ts error 2025-03-20 18:54:45 +08:00
sunnylqm
0019e9dd95 feat: add afterDownloadUpdate 2025-03-20 18:45:51 +08:00
sunnylqm
90f6b7bcb3 Add download duration and error reporting to Pushy class 2025-03-16 00:04:39 +08:00
sunnylqm
828740823d Deprecate usePushy and PushyProvider; update exports in context and index files 2025-03-15 23:43:13 +08:00
sunnylqm
135e0c5595 update deps 2025-03-15 19:08:27 +08:00
sunnylqm
06fc213da3 prevent duplicated apk download 2025-03-14 16:05:04 +08:00
29 changed files with 374 additions and 7357 deletions

1
.nvmrc
View File

@@ -1 +0,0 @@
18

File diff suppressed because it is too large Load Diff

View File

@@ -1 +0,0 @@
18

View File

@@ -12,7 +12,7 @@
"react-native-paper": "^5.13.1", "react-native-paper": "^5.13.1",
"react-native-safe-area-context": "^5.3.0", "react-native-safe-area-context": "^5.3.0",
"react-native-svg": "^15.11.2", "react-native-svg": "^15.11.2",
"react-native-update": "^10.26.0", "react-native-update": "^10.26.4",
"react-native-vector-icons": "^10.2.0", "react-native-vector-icons": "^10.2.0",
}, },
"devDependencies": { "devDependencies": {
@@ -1412,7 +1412,7 @@
"react-native-svg": ["react-native-svg@15.11.2", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-+YfF72IbWQUKzCIydlijV1fLuBsQNGMT6Da2kFlo1sh+LE3BIm/2Q7AR1zAAR6L0BFLi1WaQPLfFUC9bNZpOmw=="], "react-native-svg": ["react-native-svg@15.11.2", "", { "dependencies": { "css-select": "^5.1.0", "css-tree": "^1.1.3", "warn-once": "0.1.1" }, "peerDependencies": { "react": "*", "react-native": "*" } }, "sha512-+YfF72IbWQUKzCIydlijV1fLuBsQNGMT6Da2kFlo1sh+LE3BIm/2Q7AR1zAAR6L0BFLi1WaQPLfFUC9bNZpOmw=="],
"react-native-update": ["react-native-update@10.26.0", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-DHVIeKDx4HiVTtyOFLloLl6fwhuJ71vdVZU6Aw5i989g0s2wltVTo+HW1xqQaRgrJUwV4yOreNxKpStRWnpMXA=="], "react-native-update": ["react-native-update@10.26.4", "", { "dependencies": { "nanoid": "^3.3.3", "react-native-url-polyfill": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0", "react-native": ">=0.59.0" } }, "sha512-o7R6hOtUYk+pXijdztS0FLrdmg9pNzKagtNZloLBIa0kbPdKgbOgGpu4OLCWyo7v3Bj2mWbX1r1fxtpMHX9/UA=="],
"react-native-url-polyfill": ["react-native-url-polyfill@2.0.0", "", { "dependencies": { "whatwg-url-without-unicode": "8.0.0-3" }, "peerDependencies": { "react-native": "*" } }, "sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA=="], "react-native-url-polyfill": ["react-native-url-polyfill@2.0.0", "", { "dependencies": { "whatwg-url-without-unicode": "8.0.0-3" }, "peerDependencies": { "react-native": "*" } }, "sha512-My330Do7/DvKnEvwQc0WdcBnFPploYKp9CYlefDXzIdEaA+PAhDYllkvGeEroEzvc4Kzzj2O4yVdz8v6fjRvhA=="],

View File

@@ -1304,7 +1304,7 @@ PODS:
- ReactCommon/turbomodule/bridging - ReactCommon/turbomodule/bridging
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- Yoga - Yoga
- react-native-update (10.26.0): - react-native-update (10.26.4):
- DoubleConversion - DoubleConversion
- glog - glog
- hermes-engine - hermes-engine
@@ -1318,8 +1318,8 @@ PODS:
- React-featureflags - React-featureflags
- React-graphics - React-graphics
- React-ImageManager - React-ImageManager
- react-native-update/HDiffPatch (= 10.26.0) - react-native-update/HDiffPatch (= 10.26.4)
- react-native-update/RCTPushy (= 10.26.0) - react-native-update/RCTPushy (= 10.26.4)
- React-NativeModulesApple - React-NativeModulesApple
- React-RCTFabric - React-RCTFabric
- React-rendererdebug - React-rendererdebug
@@ -1329,7 +1329,7 @@ PODS:
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- SSZipArchive - SSZipArchive
- Yoga - Yoga
- react-native-update/HDiffPatch (10.26.0): - react-native-update/HDiffPatch (10.26.4):
- DoubleConversion - DoubleConversion
- glog - glog
- hermes-engine - hermes-engine
@@ -1352,7 +1352,7 @@ PODS:
- ReactCommon/turbomodule/core - ReactCommon/turbomodule/core
- SSZipArchive - SSZipArchive
- Yoga - Yoga
- react-native-update/RCTPushy (10.26.0): - react-native-update/RCTPushy (10.26.4):
- DoubleConversion - DoubleConversion
- glog - glog
- hermes-engine - hermes-engine
@@ -2015,7 +2015,7 @@ SPEC CHECKSUMS:
React-Mapbuffer: 3c11cee7737609275c7b66bd0b1de475f094cedf React-Mapbuffer: 3c11cee7737609275c7b66bd0b1de475f094cedf
React-microtasksnativemodule: 843f352b32aacbe13a9c750190d34df44c3e6c2c React-microtasksnativemodule: 843f352b32aacbe13a9c750190d34df44c3e6c2c
react-native-safe-area-context: 0f14bce545abcdfbff79ce2e3c78c109f0be283e react-native-safe-area-context: 0f14bce545abcdfbff79ce2e3c78c109f0be283e
react-native-update: ae3d7e91c2ce65a161769fa00e2fb0eb2b26b39e react-native-update: 7f8b9954150ff2b360fdfd999c20c16c0af2c491
React-NativeModulesApple: 88433b6946778bea9c153e27b671de15411bf225 React-NativeModulesApple: 88433b6946778bea9c153e27b671de15411bf225
React-perflogger: 9e8d3c0dc0194eb932162812a168aa5dc662f418 React-perflogger: 9e8d3c0dc0194eb932162812a168aa5dc662f418
React-performancetimeline: 5a2d6efef52bdcefac079c7baa30934978acd023 React-performancetimeline: 5a2d6efef52bdcefac079c7baa30934978acd023

View File

@@ -22,7 +22,7 @@
"react-native-paper": "^5.13.1", "react-native-paper": "^5.13.1",
"react-native-safe-area-context": "^5.3.0", "react-native-safe-area-context": "^5.3.0",
"react-native-svg": "^15.11.2", "react-native-svg": "^15.11.2",
"react-native-update": "^10.26.0", "react-native-update": "^10.26.4",
"react-native-vector-icons": "^10.2.0" "react-native-vector-icons": "^10.2.0"
}, },
"devDependencies": { "devDependencies": {
@@ -52,4 +52,4 @@
"detox", "detox",
"dtrace-provider" "dtrace-provider"
] ]
} }

View File

@@ -204,17 +204,18 @@ const styles = StyleSheet.create({
}); });
// use Pushy for China users // use Pushy for China users
// const updateClient = new Pushy({ const updateClient = new Pushy({
appKey,
debug: true,
// updateStrategy: 'silentAndLater',
});
// use Cresc for global users
// const updateClient = new Cresc({
// appKey, // appKey,
// debug: true, // debug: true,
// }); // });
// use Cresc for global users
const updateClient = new Cresc({
appKey,
debug: true,
});
export default function Root() { export default function Root() {
return ( return (
<UpdateProvider client={updateClient}> <UpdateProvider client={updateClient}>
@@ -223,4 +224,4 @@ export default function Root() {
</PaperProvider> </PaperProvider>
</UpdateProvider> </UpdateProvider>
); );
} }

View File

@@ -7,4 +7,4 @@
"appId": 27509, "appId": 27509,
"appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY" "appKey": "aQz3Uc2pA7gt_prDaQ4rbWRY"
} }
} }

View File

@@ -22,14 +22,42 @@ def supportsNamespace() {
return major >= 8 return major >= 8
} }
def isExpoProject() {
def hasExpoModulesCore = rootProject.subprojects.any { it.name == 'expo-modules-core' }
def packageJsonFile = new File(rootProject.projectDir.parentFile, 'package.json')
def hasExpoDependency = false
if (packageJsonFile.exists()) {
def packageJson = new groovy.json.JsonSlurper().parseText(packageJsonFile.text)
hasExpoDependency = (packageJson.dependencies?.expo != null) ||
(packageJson.devDependencies?.expo != null)
}
return hasExpoModulesCore || hasExpoDependency
}
def expoProject = isExpoProject()
apply plugin: 'com.android.library' apply plugin: 'com.android.library'
if (isNewArchitectureEnabled()) { if (isNewArchitectureEnabled()) {
apply plugin: 'com.facebook.react' apply plugin: 'com.facebook.react'
} }
if (expoProject) {
group = 'expo.modules.pushy'
version = '1.0.0'
def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle")
apply from: expoModulesCorePlugin
applyKotlinExpoModulesCorePlugin()
useCoreDependencies()
useExpoPublishing()
} else {
group = 'cn.reactnative.modules.update'
version = '1.0.0'
}
android { android {
if (supportsNamespace()) { if (supportsNamespace()) {
namespace "cn.reactnative.modules.update" namespace "cn.reactnative.modules.update"
@@ -41,7 +69,6 @@ android {
} }
compileSdkVersion safeExtGet('compileSdkVersion', 28) compileSdkVersion safeExtGet('compileSdkVersion', 28)
buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3') buildToolsVersion safeExtGet('buildToolsVersion', '28.0.3')
defaultConfig { defaultConfig {
minSdkVersion safeExtGet('minSdkVersion', 16) minSdkVersion safeExtGet('minSdkVersion', 16)
targetSdkVersion safeExtGet('targetSdkVersion', 27) targetSdkVersion safeExtGet('targetSdkVersion', 27)
@@ -50,6 +77,7 @@ android {
consumerProguardFiles "proguard.pro" consumerProguardFiles "proguard.pro"
buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
} }
sourceSets { sourceSets {
main { main {
// let gradle pack the shared library into apk // let gradle pack the shared library into apk
@@ -59,6 +87,12 @@ android {
} else { } else {
java.srcDirs += ['src/oldarch'] java.srcDirs += ['src/oldarch']
} }
if (expoProject) {
java.srcDirs += ['java/expo/modules/pushy']
} else {
java.exclude 'expo/modules/pushy/**'
}
} }
} }
@@ -70,6 +104,10 @@ android {
resValue("string", "pushy_build_time", "0") resValue("string", "pushy_build_time", "0")
} }
} }
lintOptions {
abortOnError false
}
} }
repositories { repositories {

View File

@@ -0,0 +1,13 @@
package cn.reactnative.modules.update;
import androidx.annotation.Nullable;
public interface ReactNativeHostHandler {
@Nullable
String getJSBundleFile(boolean useDeveloperSupport);
@Nullable
String getBundleAssetName(boolean useDeveloperSupport);
void onWillCreateReactInstance(boolean useDeveloperSupport);
}

View File

@@ -7,14 +7,11 @@ import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.os.Environment; import android.os.Environment;
import android.util.Log; import android.util.Log;
import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactInstanceManager;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.io.File; import java.io.File;
public class UpdateContext { public class UpdateContext {

View File

@@ -176,6 +176,35 @@ public class UpdateModuleImpl {
}); });
} }
public static void restartApp(final ReactApplicationContext mContext, Promise promise) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
final Context application = mContext.getApplicationContext();
ReactInstanceManager instanceManager = ((ReactApplication) application).getReactNativeHost().getReactInstanceManager();
instanceManager.recreateReactContextInBackground();
promise.resolve(true);
} catch (Throwable err) {
promise.reject("restartApp failed: "+err.getMessage());
Log.e("pushy", "restartApp failed", err);
final Activity currentActivity = mContext.getCurrentActivity();
if (currentActivity == null) {
return;
}
currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
currentActivity.recreate();
}
});
}
}
});
}
public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options, Promise promise) { public static void setNeedUpdate(UpdateContext updateContext, ReadableMap options, Promise promise) {
final String hash = options.getString("hash"); final String hash = options.getString("hash");

View File

@@ -0,0 +1,10 @@
package expo.modules.pushy
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class ExpoPushyModule : Module() {
override fun definition() = ModuleDefinition {
Name("ExpoPushy")
}
}

View File

@@ -0,0 +1,27 @@
package expo.modules.pushy;
import android.content.Context;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.reactnative.modules.update.UpdateContext;
import expo.modules.core.interfaces.Package;
import expo.modules.core.interfaces.ReactNativeHostHandler;
public class ExpoPushyPackage implements Package {
@Override
public List<ReactNativeHostHandler> createReactNativeHostHandlers(Context context) {
List<ReactNativeHostHandler> handlers = new ArrayList<>();
handlers.add(new ReactNativeHostHandler() {
@Nullable
@Override
public String getJSBundleFile(boolean useDeveloperSupport) {
return UpdateContext.getBundleUrl(context);
}
});
return handlers;
}
}

View File

@@ -97,6 +97,11 @@ public class UpdateModule extends NativePushySpec {
UpdateModuleImpl.reloadUpdate(updateContext, mContext, options,promise); UpdateModuleImpl.reloadUpdate(updateContext, mContext, options,promise);
} }
@Override
public void restartApp(Promise promise) {
UpdateModuleImpl.restartApp(mContext, promise);
}
@Override @Override
public void setNeedUpdate(ReadableMap options,Promise promise) { public void setNeedUpdate(ReadableMap options,Promise promise) {
UpdateModuleImpl.setNeedUpdate(updateContext, options,promise); UpdateModuleImpl.setNeedUpdate(updateContext, options,promise);

View File

@@ -224,6 +224,29 @@ public class UpdateModule extends ReactContextBaseJavaModule {
}); });
} }
@ReactMethod
public void restartApp(final Promise promise) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
final Context application = getReactApplicationContext().getApplicationContext();
ReactInstanceManager instanceManager = updateContext.getCustomReactInstanceManager();
if (instanceManager == null) {
instanceManager = ((ReactApplication) application).getReactNativeHost().getReactInstanceManager();
}
instanceManager.recreateReactContextInBackground();
promise.resolve(true);
} catch (Throwable err) {
promise.reject(err);
Log.e("pushy", "restartApp failed ", err);
}
}
});
}
@ReactMethod @ReactMethod
public void setNeedUpdate(ReadableMap options) { public void setNeedUpdate(ReadableMap options) {
final String hash = options.getString("hash"); final String hash = options.getString("hash");

13
expo-module.config.json Normal file
View File

@@ -0,0 +1,13 @@
{
"platforms": ["apple", "android"],
"apple": {
"modules": ["ExpoPushyModule"],
"reactDelegateHandlers": ["ExpoPushyReactDelegateHandler"],
"podspecPath":"react-native-update.podspec"
},
"android": {
"modules": [
"expo.modules.pushy.ExpoPushyModule"
]
}
}

View File

@@ -0,0 +1,7 @@
import ExpoModulesCore
public class ExpoPushyModule: Module {
public func definition() -> ModuleDefinition {
Name("ExpoPushy")
}
}

View File

@@ -0,0 +1,10 @@
import ExpoModulesCore
import react_native_update
public final class ExpoPushyReactDelegateHandler: ExpoReactDelegateHandler {
private weak var reactDelegate: ExpoReactDelegate?
public override func bundleURL(reactDelegate: ExpoReactDelegate) -> URL? {
return RCTPushy.bundleURL()
}
}

View File

@@ -338,6 +338,26 @@ RCT_EXPORT_METHOD(reloadUpdate:(NSDictionary *)options
} }
} }
RCT_EXPORT_METHOD(restartApp:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
@try {
dispatch_async(dispatch_get_main_queue(), ^{
[self.bridge reload];
});
#if __has_include("RCTReloadCommand.h")
// reload 0.62+
RCTReloadCommandSetBundleURL([[self class] bundleURL]);
RCTTriggerReloadCommandListeners(@"pushy restartApp");
#endif
resolve(@true);
}
@catch (NSException *exception) {
reject(@"执行报错", exception.reason, nil);
}
}
RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) rejecter:(RCTPromiseRejectBlock)reject)
{ {

View File

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

View File

@@ -19,7 +19,7 @@ Pod::Spec.new do |s|
s.platform = :ios, "8.0" s.platform = :ios, "8.0"
s.platforms = { :ios => "11.0" } s.platforms = { :ios => "11.0" }
s.source = { :git => 'https://github.com/reactnativecn/react-native-update.git', :tag => '#{s.version}' } s.source = { :git => 'https://github.com/reactnativecn/react-native-update.git', :tag => '#{s.version}' }
s.source_files = "ios/**/*.{h,m,mm,swift}" s.source_files = Dir.glob("ios/**/*.{h,m,mm,swift}").reject { |f| f.start_with?("ios/Expo/") }
s.libraries = 'bz2', 'z' s.libraries = 'bz2', 'z'
s.vendored_libraries = 'RCTPushy/libRCTPushy.a' s.vendored_libraries = 'RCTPushy/libRCTPushy.a'
s.pod_target_xcconfig = { s.pod_target_xcconfig = {
@@ -33,11 +33,25 @@ Pod::Spec.new do |s|
s.dependency "React-Core" s.dependency "React-Core"
s.dependency 'SSZipArchive' s.dependency 'SSZipArchive'
project_root = File.expand_path('../../', __dir__)
project_package_json = File.join(project_root, 'package.json')
is_expo_project = false
if (File.exist?(project_package_json))
package_json = JSON.parse(File.read(project_package_json))
has_expo_dependency = package_json['dependencies'] && package_json['dependencies']['expo']
has_expo_modules_core = Dir.exist?('node_modules/expo-modules-core')
is_expo_project = has_expo_dependency || has_expo_modules_core
if is_expo_project
s.dependency 'ExpoModulesCore'
end
end
s.subspec 'RCTPushy' do |ss| s.subspec 'RCTPushy' do |ss|
ss.source_files = 'ios/RCTPushy/*.{h,m,mm,swift}' ss.source_files = 'ios/RCTPushy/*.{h,m,mm,swift}'
ss.public_header_files = ['ios/RCTPushy/RCTPushy.h'] ss.public_header_files = ['ios/RCTPushy/RCTPushy.h']
end end
s.subspec 'HDiffPatch' do |ss| s.subspec 'HDiffPatch' do |ss|
ss.source_files = ['ios/RCTPushy/HDiffPatch/**/*.{h,m,c}', ss.source_files = ['ios/RCTPushy/HDiffPatch/**/*.{h,m,c}',
'android/jni/hpatch.{h,c}', 'android/jni/hpatch.{h,c}',
@@ -47,7 +61,13 @@ Pod::Spec.new do |s|
'android/jni/lzma/C/Lzma2Dec.{h,c}'] 'android/jni/lzma/C/Lzma2Dec.{h,c}']
ss.public_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h' ss.public_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
end end
if is_expo_project
s.subspec 'Expo' do |ss|
ss.source_files = 'ios/Expo/**/*.{h,m,mm,swift}'
end
end
if defined?(install_modules_dependencies()) != nil if defined?(install_modules_dependencies()) != nil
install_modules_dependencies(s); install_modules_dependencies(s);
else else
@@ -60,7 +80,6 @@ Pod::Spec.new do |s|
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"", "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17" "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
} }
s.dependency "React-Codegen" s.dependency "React-Codegen"
s.dependency "RCT-Folly" s.dependency "RCT-Folly"
s.dependency "RCTRequired" s.dependency "RCTRequired"

View File

@@ -15,6 +15,7 @@ export interface Spec extends TurboModule {
getLocalHashInfo(hash: string): Promise<string>; getLocalHashInfo(hash: string): Promise<string>;
setUuid(uuid: string): Promise<void>; setUuid(uuid: string): Promise<void>;
reloadUpdate(options: { hash: string }): Promise<void>; reloadUpdate(options: { hash: string }): Promise<void>;
restartApp(): Promise<void>;
setNeedUpdate(options: { hash: string }): Promise<void>; setNeedUpdate(options: { hash: string }): Promise<void>;
markSuccess(): Promise<void>; markSuccess(): Promise<void>;
downloadPatchFromPpk(options: { downloadPatchFromPpk(options: {

View File

@@ -26,6 +26,7 @@ import {
setLocalHashInfo, setLocalHashInfo,
isFirstTime, isFirstTime,
isRolledBack, isRolledBack,
getCurrentVersionInfo,
} from './core'; } from './core';
const SERVER_PRESETS = { const SERVER_PRESETS = {
@@ -60,6 +61,31 @@ const defaultClientOptions: ClientOptions = {
throwError: false, throwError: false,
}; };
export const sharedState: {
progressHandlers: Record<string, EmitterSubscription>;
downloadedHash?: string;
apkStatus: 'downloading' | 'downloaded' | null;
marked: boolean;
applyingUpdate: boolean;
} = {
progressHandlers: {},
downloadedHash: undefined,
apkStatus: null,
marked: false,
applyingUpdate: false,
};
const assertHash = (hash: string) => {
if (!sharedState.downloadedHash) {
return;
}
if (hash !== sharedState.downloadedHash) {
log(`use downloaded hash ${sharedState.downloadedHash} first`);
return;
}
return true;
};
// for China users // for China users
export class Pushy { export class Pushy {
options = defaultClientOptions; options = defaultClientOptions;
@@ -67,13 +93,6 @@ export class Pushy {
lastChecking?: number; lastChecking?: number;
lastRespJson?: Promise<any>; lastRespJson?: Promise<any>;
static progressHandlers: Record<string, EmitterSubscription> = {};
static downloadedHash?: string;
static apkStatus: 'downloading' | 'downloaded' | null = null;
static marked = false;
static applyingUpdate = false;
version = cInfo.rnu; version = cInfo.rnu;
loggerPromise = (() => { loggerPromise = (() => {
let resolve: (value?: unknown) => void = () => {}; let resolve: (value?: unknown) => void = () => {};
@@ -128,6 +147,7 @@ export class Pushy {
log(type + ' ' + message); log(type + ' ' + message);
await this.loggerPromise.promise; await this.loggerPromise.promise;
const { logger = noop, appKey } = this.options; const { logger = noop, appKey } = this.options;
const info = await getCurrentVersionInfo();
logger({ logger({
type, type,
data: { data: {
@@ -137,6 +157,7 @@ export class Pushy {
packageVersion, packageVersion,
buildTime, buildTime,
message, message,
...info,
...data, ...data,
}, },
}); });
@@ -149,16 +170,6 @@ export class Pushy {
getCheckUrl = (endpoint: string = this.options.server!.main) => { getCheckUrl = (endpoint: string = this.options.server!.main) => {
return `${endpoint}/checkUpdate/${this.options.appKey}`; return `${endpoint}/checkUpdate/${this.options.appKey}`;
}; };
static assertHash = (hash: string) => {
if (!this.downloadedHash) {
return;
}
if (hash !== this.downloadedHash) {
log(`use downloaded hash ${Pushy.downloadedHash} first`);
return;
}
return true;
};
assertDebug = () => { assertDebug = () => {
if (__DEV__ && !this.options.debug) { if (__DEV__ && !this.options.debug) {
console.info( console.info(
@@ -169,10 +180,10 @@ export class Pushy {
return true; return true;
}; };
markSuccess = () => { markSuccess = () => {
if (Pushy.marked || __DEV__ || !isFirstTime) { if (sharedState.marked || __DEV__ || !isFirstTime) {
return; return;
} }
Pushy.marked = true; sharedState.marked = true;
PushyModule.markSuccess(); PushyModule.markSuccess();
this.report({ type: 'markSuccess' }); this.report({ type: 'markSuccess' });
}; };
@@ -180,9 +191,9 @@ export class Pushy {
if (!assertDev('switchVersion()')) { if (!assertDev('switchVersion()')) {
return; return;
} }
if (Pushy.assertHash(hash) && !Pushy.applyingUpdate) { if (assertHash(hash) && !sharedState.applyingUpdate) {
log('switchVersion: ' + hash); log('switchVersion: ' + hash);
Pushy.applyingUpdate = true; sharedState.applyingUpdate = true;
return PushyModule.reloadUpdate({ hash }); return PushyModule.reloadUpdate({ hash });
} }
}; };
@@ -191,7 +202,7 @@ export class Pushy {
if (!assertDev('switchVersionLater()')) { if (!assertDev('switchVersionLater()')) {
return; return;
} }
if (Pushy.assertHash(hash)) { if (assertHash(hash)) {
log('switchVersionLater: ' + hash); log('switchVersionLater: ' + hash);
return PushyModule.setNeedUpdate({ hash }); return PushyModule.setNeedUpdate({ hash });
} }
@@ -346,17 +357,18 @@ export class Pushy {
log(`rolledback hash ${rolledBackVersion}, ignored`); log(`rolledback hash ${rolledBackVersion}, ignored`);
return; return;
} }
if (Pushy.downloadedHash === hash) { if (sharedState.downloadedHash === hash) {
log(`duplicated downloaded hash ${Pushy.downloadedHash}, ignored`); log(`duplicated downloaded hash ${sharedState.downloadedHash}, ignored`);
return Pushy.downloadedHash; return sharedState.downloadedHash;
} }
if (Pushy.progressHandlers[hash]) { if (sharedState.progressHandlers[hash]) {
return; return;
} }
const patchStartTime = Date.now();
if (onDownloadProgress) { if (onDownloadProgress) {
// @ts-expect-error harmony not in existing platforms // @ts-expect-error harmony not in existing platforms
if (Platform.OS === 'harmony') { if (Platform.OS === 'harmony') {
Pushy.progressHandlers[hash] = DeviceEventEmitter.addListener( sharedState.progressHandlers[hash] = DeviceEventEmitter.addListener(
'RCTPushyDownloadProgress', 'RCTPushyDownloadProgress',
progressData => { progressData => {
if (progressData.hash === hash) { if (progressData.hash === hash) {
@@ -365,14 +377,15 @@ export class Pushy {
}, },
); );
} else { } else {
Pushy.progressHandlers[hash] = pushyNativeEventEmitter.addListener( sharedState.progressHandlers[hash] =
'RCTPushyDownloadProgress', pushyNativeEventEmitter.addListener(
progressData => { 'RCTPushyDownloadProgress',
if (progressData.hash === hash) { progressData => {
onDownloadProgress(progressData); if (progressData.hash === hash) {
} onDownloadProgress(progressData);
}, }
); },
);
} }
} }
let succeeded = ''; let succeeded = '';
@@ -440,9 +453,9 @@ export class Pushy {
} }
} }
} }
if (Pushy.progressHandlers[hash]) { if (sharedState.progressHandlers[hash]) {
Pushy.progressHandlers[hash].remove(); sharedState.progressHandlers[hash].remove();
delete Pushy.progressHandlers[hash]; delete sharedState.progressHandlers[hash];
} }
if (__DEV__) { if (__DEV__) {
return hash; return hash;
@@ -458,9 +471,18 @@ export class Pushy {
} }
return; return;
} else { } else {
const duration = Date.now() - patchStartTime;
const data: Record<string, any> = {
newVersion: hash,
diff: succeeded,
duration,
};
if (errorMessages.length > 0) {
data.error = errorMessages.join(';');
}
this.report({ this.report({
type: 'downloadSuccess', type: 'downloadSuccess',
data: { newVersion: hash, diff: succeeded }, data,
}); });
} }
log(`downloaded ${succeeded} hash:`, hash); log(`downloaded ${succeeded} hash:`, hash);
@@ -469,7 +491,7 @@ export class Pushy {
description, description,
metaInfo, metaInfo,
}); });
Pushy.downloadedHash = hash; sharedState.downloadedHash = hash;
return hash; return hash;
}; };
downloadAndInstallApk = async ( downloadAndInstallApk = async (
@@ -479,10 +501,10 @@ export class Pushy {
if (Platform.OS !== 'android') { if (Platform.OS !== 'android') {
return; return;
} }
if (Pushy.apkStatus === 'downloading') { if (sharedState.apkStatus === 'downloading') {
return; return;
} }
if (Pushy.apkStatus === 'downloaded') { if (sharedState.apkStatus === 'downloaded') {
this.report({ type: 'errorInstallApk' }); this.report({ type: 'errorInstallApk' });
this.throwIfEnabled(new Error('errorInstallApk')); this.throwIfEnabled(new Error('errorInstallApk'));
return; return;
@@ -503,37 +525,41 @@ export class Pushy {
return; return;
} }
} }
Pushy.apkStatus = 'downloading'; sharedState.apkStatus = 'downloading';
this.report({ type: 'downloadingApk' }); this.report({ type: 'downloadingApk' });
const progressKey = 'downloadingApk'; const progressKey = 'downloadingApk';
if (onDownloadProgress) { if (onDownloadProgress) {
if (Pushy.progressHandlers[progressKey]) { if (sharedState.progressHandlers[progressKey]) {
Pushy.progressHandlers[progressKey].remove(); sharedState.progressHandlers[progressKey].remove();
} }
Pushy.progressHandlers[progressKey] = pushyNativeEventEmitter.addListener( sharedState.progressHandlers[progressKey] =
'RCTPushyDownloadProgress', pushyNativeEventEmitter.addListener(
(progressData: ProgressData) => { 'RCTPushyDownloadProgress',
if (progressData.hash === progressKey) { (progressData: ProgressData) => {
onDownloadProgress(progressData); if (progressData.hash === progressKey) {
} onDownloadProgress(progressData);
}, }
); },
);
} }
await PushyModule.downloadAndInstallApk({ await PushyModule.downloadAndInstallApk({
url, url,
target: 'update.apk', target: 'update.apk',
hash: progressKey, hash: progressKey,
}).catch(() => { }).catch(() => {
Pushy.apkStatus = null; sharedState.apkStatus = null;
this.report({ type: 'errorDownloadAndInstallApk' }); this.report({ type: 'errorDownloadAndInstallApk' });
this.throwIfEnabled(new Error('errorDownloadAndInstallApk')); this.throwIfEnabled(new Error('errorDownloadAndInstallApk'));
}); });
Pushy.apkStatus = 'downloaded'; sharedState.apkStatus = 'downloaded';
if (Pushy.progressHandlers[progressKey]) { if (sharedState.progressHandlers[progressKey]) {
Pushy.progressHandlers[progressKey].remove(); sharedState.progressHandlers[progressKey].remove();
delete Pushy.progressHandlers[progressKey]; delete sharedState.progressHandlers[progressKey];
} }
}; };
restartApp = async () => {
return PushyModule.restartApp();
};
} }
// for international users // for international users

View File

@@ -13,6 +13,7 @@ export const defaultContext = {
dismissError: noop, dismissError: noop,
downloadUpdate: asyncNoop, downloadUpdate: asyncNoop,
downloadAndInstallApk: asyncNoop, downloadAndInstallApk: asyncNoop,
restartApp: asyncNoop,
getCurrentVersionInfo: () => Promise.resolve({}), getCurrentVersionInfo: () => Promise.resolve({}),
parseTestQrCode: () => false, parseTestQrCode: () => false,
currentHash: '', currentHash: '',
@@ -33,6 +34,7 @@ export const UpdateContext = createContext<{
metaInfo?: string; metaInfo?: string;
}>; }>;
parseTestQrCode: (code: string) => boolean; parseTestQrCode: (code: string) => boolean;
restartApp: () => Promise<void>;
currentHash: string; currentHash: string;
packageVersion: string; packageVersion: string;
client?: Pushy | Cresc; client?: Pushy | Cresc;
@@ -43,6 +45,5 @@ export const UpdateContext = createContext<{
export const useUpdate = () => useContext(UpdateContext); export const useUpdate = () => useContext(UpdateContext);
/** @deprecated Please use `useUpdate` instead */
export const usePushy = useUpdate; export const usePushy = useUpdate;
export const useCresc = useUpdate;

View File

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

View File

@@ -12,7 +12,7 @@ import {
Platform, Platform,
Linking, Linking,
} from 'react-native'; } from 'react-native';
import { Pushy, Cresc } from './client'; import { Pushy, Cresc, sharedState } from './client';
import { currentVersion, packageVersion, getCurrentVersionInfo } from './core'; import { currentVersion, packageVersion, getCurrentVersionInfo } from './core';
import { CheckResult, ProgressData, UpdateTestPayload } from './type'; import { CheckResult, ProgressData, UpdateTestPayload } from './type';
import { UpdateContext } from './context'; import { UpdateContext } from './context';
@@ -100,6 +100,14 @@ export const UpdateProvider = ({
return false; return false;
} }
stateListener.current && stateListener.current.remove(); stateListener.current && stateListener.current.remove();
if (
options.afterDownloadUpdate &&
(await options.afterDownloadUpdate(info)) === false
) {
log('afterDownloadUpdate returned false, skipping');
return false;
}
if (options.updateStrategy === 'silentAndNow') { if (options.updateStrategy === 'silentAndNow') {
client.switchVersion(hash); client.switchVersion(hash);
return true; return true;
@@ -131,13 +139,7 @@ export const UpdateProvider = ({
return false; return false;
} }
}, },
[ [client, options, alertUpdate, alertError, throwErrorIfEnabled],
client,
options.updateStrategy,
alertUpdate,
alertError,
throwErrorIfEnabled,
],
); );
const downloadAndInstallApk = useCallback( const downloadAndInstallApk = useCallback(
@@ -169,7 +171,7 @@ export const UpdateProvider = ({
return; return;
} }
const rollout = info.config?.rollout?.[packageVersion]; const rollout = info.config?.rollout?.[packageVersion];
if (rollout) { if (info.update && rollout) {
if (!isInRollout(rollout)) { if (!isInRollout(rollout)) {
log(`not in ${rollout}% rollout, ignored`); log(`not in ${rollout}% rollout, ignored`);
return; return;
@@ -180,8 +182,15 @@ export const UpdateProvider = ({
updateInfoRef.current = info; updateInfoRef.current = info;
setUpdateInfo(info); setUpdateInfo(info);
if (info.expired) { if (info.expired) {
if (
options.onPackageExpired &&
(await options.onPackageExpired(info)) === false
) {
log('onPackageExpired returned false, skipping');
return;
}
const { downloadUrl } = info; const { downloadUrl } = info;
if (downloadUrl) { if (downloadUrl && sharedState.apkStatus === null) {
if (options.updateStrategy === 'silentAndNow') { if (options.updateStrategy === 'silentAndNow') {
if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) { if (Platform.OS === 'android' && downloadUrl.endsWith('.apk')) {
downloadAndInstallApk(downloadUrl); downloadAndInstallApk(downloadUrl);
@@ -232,7 +241,7 @@ export const UpdateProvider = ({
client, client,
alertError, alertError,
throwErrorIfEnabled, throwErrorIfEnabled,
options.updateStrategy, options,
alertUpdate, alertUpdate,
downloadAndInstallApk, downloadAndInstallApk,
downloadUpdate, downloadUpdate,
@@ -314,6 +323,10 @@ export const UpdateProvider = ({
[parseTestPayload], [parseTestPayload],
); );
const restartApp = useCallback(async () => {
return client.restartApp();
}, [client]);
useEffect(() => { useEffect(() => {
const parseLinking = (url: string | null) => { const parseLinking = (url: string | null) => {
if (!url) { if (!url) {
@@ -359,10 +372,12 @@ export const UpdateProvider = ({
downloadAndInstallApk, downloadAndInstallApk,
getCurrentVersionInfo, getCurrentVersionInfo,
parseTestQrCode, parseTestQrCode,
restartApp,
}}> }}>
{children} {children}
</UpdateContext.Provider> </UpdateContext.Provider>
); );
}; };
/** @deprecated Please use `UpdateProvider` instead */
export const PushyProvider = UpdateProvider; export const PushyProvider = UpdateProvider;

View File

@@ -54,6 +54,9 @@ export interface EventData {
message?: string; message?: string;
rolledBackVersion?: string; rolledBackVersion?: string;
newVersion?: string; newVersion?: string;
name?: string;
description?: string;
metaInfo?: string;
[key: string]: any; [key: string]: any;
} }
@@ -88,6 +91,8 @@ export interface ClientOptions {
throwError?: boolean; throwError?: boolean;
beforeCheckUpdate?: () => Promise<boolean>; beforeCheckUpdate?: () => Promise<boolean>;
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>; beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
afterDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
onPackageExpired?: (info: CheckResult) => Promise<boolean>;
} }
export interface UpdateTestPayload { export interface UpdateTestPayload {

View File

@@ -49,20 +49,20 @@ const ping =
return url; return url;
} }
log('ping failed', url, status, statusText); log('ping failed', url, status, statusText);
return null; throw new Error('Ping failed');
}) })
.catch(e => { .catch(e => {
pingFinished = true; pingFinished = true;
log('ping error', url, e); log('ping error', url, e);
return null; throw e;
}), }),
new Promise(r => new Promise((_, reject) =>
setTimeout(() => { setTimeout(() => {
r(null); reject(new Error('Ping timeout'));
if (!pingFinished) { if (!pingFinished) {
log('ping timeout', url); log('ping timeout', url);
} }
}, 2000), }, 5000),
), ),
]); ]);
}; };
@@ -77,10 +77,14 @@ export const testUrls = async (urls?: string[]) => {
if (!urls?.length) { if (!urls?.length) {
return null; return null;
} }
const ret = await promiseAny(urls.map(ping));
if (ret) { try {
return ret; const ret = await promiseAny(urls.map(ping));
} if (ret) {
log('ping success, use url:', ret);
return ret;
}
} catch {}
log('all ping failed, use first url:', urls[0]); log('all ping failed, use first url:', urls[0]);
return urls[0]; return urls[0];
}; };