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

Compare commits

..

5 Commits

Author SHA1 Message Date
sunnylqm
7152ef7304 v9.0.0-beta.3 2023-09-02 22:49:12 +08:00
sunnylqm
094eb3f267 chore: cleanup 2023-09-02 22:40:55 +08:00
sunnylqm
6d01ce5152 chore: cleanup 2023-09-02 22:35:45 +08:00
sunnylqm
8bf1fed3f8 v9.0.0-beta.2 2023-09-02 21:07:04 +08:00
sunnylqm
39c4a6d339 feat: onEvents 2023-08-31 19:24:00 +08:00
13 changed files with 250 additions and 221 deletions

View File

@@ -1,5 +1,5 @@
#import "AppDelegate.h"
#import "RCTPushy.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@@ -87,7 +87,7 @@ static NSString *const kRNConcurrentRoot = @"concurrentRoot";
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
return [RCTPushy bundleURL];
#endif
}

View File

@@ -24,6 +24,19 @@
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>UILaunchStoryboardName</key>
@@ -40,18 +53,5 @@
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
</dict>
</plist>

View File

@@ -53,6 +53,7 @@ typedef NS_ENUM(NSInteger, PushyType) {
};
static BOOL ignoreRollback = false;
static BOOL isUsingBundleUrl = false;
@implementation RCTPushy {
RCTPushyManager *_fileManager;
@@ -65,6 +66,7 @@ RCT_EXPORT_MODULE(RCTPushy);
+ (NSURL *)bundleURL
{
isUsingBundleUrl = true;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
@@ -161,6 +163,7 @@ RCT_EXPORT_MODULE(RCTPushy);
ret[@"uuid"] = [defaults objectForKey:keyUuid];
NSDictionary *pushyInfo = [defaults dictionaryForKey:keyPushyInfo];
ret[@"currentVersion"] = [pushyInfo objectForKey:paramCurrentVersion];
ret[@"isUsingBundleUrl"] = @(isUsingBundleUrl);
// clear isFirstTimemarked
if (ret[@"isFirstTime"]) {

View File

@@ -1,51 +1,45 @@
/**
* @format
* @flow strict-local
*/
'use strict';
import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
getConstants: () => {
downloadRootDir: string,
packageVersion: string,
currentVersion: string,
isFirstTime: boolean,
rolledBackVersion: string,
buildTime: string,
blockUpdate: Object,
uuid: string,
isUsingBundleUrl: boolean,
downloadRootDir: string;
packageVersion: string;
currentVersion: string;
isFirstTime: boolean;
rolledBackVersion: string;
buildTime: string;
blockUpdate: Object;
uuid: string;
isUsingBundleUrl: boolean;
};
setLocalHashInfo(hash: string, info: string): Promise<void>;
getLocalHashInfo(hash: string): Promise<string>;
setUuid(uuid: string): Promise<void>;
setBlockUpdate(options: { reason: string, until: number }): Promise<void>;
setBlockUpdate(options: { reason: string; until: number }): Promise<void>;
reloadUpdate(options: { hash: string }): Promise<void>;
setNeedUpdate(options: { hash: string }): Promise<void>;
markSuccess(): Promise<void>;
downloadPatchFromPpk(options: {
updateUrl: string,
hash: string,
originHash: string,
updateUrl: string;
hash: string;
originHash: string;
}): Promise<void>;
downloadPatchFromPackage(options: {
updateUrl: string,
hash: string,
updateUrl: string;
hash: string;
}): Promise<void>;
downloadFullUpdate(options: {
updateUrl: string,
hash: string,
updateUrl: string;
hash: string;
}): Promise<void>;
downloadAndInstallApk(options: {
url: string,
target: string,
hash: string,
url: string;
target: string;
hash: string;
}): Promise<void>;
addListener(eventName: string): void;
removeListeners(count: number): void;
}
export default (TurboModuleRegistry.get<Spec>('Pushy'): ?Spec);
export default TurboModuleRegistry.get<Spec>('Pushy') as Spec | null;

View File

@@ -1,6 +1,6 @@
let currentEndpoint = 'https://update.react-native.cn/api';
function ping(url, rejectImmediate) {
function ping(url: string, rejectImmediate?: boolean) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => {
@@ -20,12 +20,12 @@ function ping(url, rejectImmediate) {
});
}
function logger(...args) {
// console.warn('pushy', ...args);
function logger(...args: any[]) {
console.log('Pushy: ', ...args);
}
let backupEndpoints = [];
let backupEndpointsQueryUrl =
let backupEndpoints: string[] = [];
let backupEndpointsQueryUrl: string | null =
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json';
export async function tryBackupEndpoints() {
@@ -34,10 +34,10 @@ export async function tryBackupEndpoints() {
}
try {
await ping(getStatusUrl(), true);
logger('current endpoint ok');
logger('current endpoint ok', currentEndpoint);
return;
} catch (e) {
logger('current endpoint failed');
logger('current endpoint failed', currentEndpoint);
}
if (!backupEndpoints.length && backupEndpointsQueryUrl) {
try {
@@ -76,11 +76,21 @@ export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
return `${endpoint}/checkUpdate/${APPKEY}`;
}
export function getReportUrl(endpoint = currentEndpoint) {
return `${endpoint}/report`;
}
export function setCustomEndpoints({ main, backups, backupQueryUrl }) {
/**
* @param {string} main - The main api endpoint
* @param {string[]} [backups] - The back up endpoints.
* @param {string} [backupQueryUrl] - An url that return a json file containing an array of endpoint.
* like: ["https://backup.api/1", "https://backup.api/2"]
*/
export function setCustomEndpoints({
main,
backups,
backupQueryUrl,
}: {
main: string;
backups?: string[];
backupQueryUrl?: string;
}) {
currentEndpoint = main;
backupEndpointsQueryUrl = null;
if (Array.isArray(backups) && backups.length > 0) {

94
lib/index.d.ts vendored
View File

@@ -1,94 +0,0 @@
export const downloadRootDir: string;
export const packageVersion: string;
export const currentVersion: string;
export const isFirstTime: boolean;
export const isRolledBack: boolean;
export interface ExpiredResult {
upToDate?: false;
expired: true;
downloadUrl: string;
}
export interface UpTodateResult {
expired?: false;
upToDate: true;
paused?: 'app' | 'package';
}
export interface UpdateAvailableResult {
expired?: false;
upToDate?: false;
update: true;
name: string; // version name
hash: string;
description: string;
metaInfo: string;
pdiffUrl: string;
diffUrl?: string;
}
export type CheckResult =
| ExpiredResult
| UpTodateResult
| UpdateAvailableResult;
export function checkUpdate(appkey: string): Promise<CheckResult>;
export function downloadUpdate(
info: UpdateAvailableResult,
eventListeners?: {
onDownloadProgress?: (data: ProgressData) => void;
},
): Promise<undefined | string>;
export function switchVersion(hash: string): void;
export function switchVersionLater(hash: string): void;
export function markSuccess(): void;
export function downloadAndInstallApk({
url,
onDownloadProgress,
}: {
url: string;
onDownloadProgress?: (data: ProgressData) => void;
}): Promise<void>;
/**
* @param {string} main - The main api endpoint
* @param {string[]} [backups] - The back up endpoints.
* @param {string} [backupQueryUrl] - An url that return a json file containing an array of endpoint.
* like: ["https://backup.api/1", "https://backup.api/2"]
*/
export function setCustomEndpoints({
main,
backups,
backupQueryUrl,
}: {
main: string;
backups?: string[];
backupQueryUrl?: string;
}): void;
export function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;
metaInfo?: string;
}>;
interface ProgressData {
hash: string;
received: number;
total: number;
}
interface SimpleUpdateOptions {
appKey: string;
}
export function simpleUpdate(
wrappedComponent: any,
options: SimpleUpdateOptions,
): any;

View File

@@ -15,3 +15,4 @@ export const downloadAndInstallApk = noop;
export const setCustomEndpoints = noop;
export const getCurrentVersionInfo = noop;
export const simpleUpdate = noop;
export const onEvents = noop;

View File

@@ -2,7 +2,6 @@ import {
tryBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
getReportUrl,
} from './endpoint';
import {
NativeEventEmitter,
@@ -10,6 +9,12 @@ import {
Platform,
PermissionsAndroid,
} from 'react-native';
import {
EventType,
ProgressData,
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
export { setCustomEndpoints };
const {
version: v,
@@ -39,21 +44,25 @@ export const buildTime = PushyConstants.buildTime;
let blockUpdate = PushyConstants.blockUpdate;
let uuid = PushyConstants.uuid;
if (Platform.OS === 'android' && !PushyConstants.isUsingBundleUrl) {
if (!PushyConstants.isUsingBundleUrl) {
throw new Error(
'react-native-update模块无法加载请对照文档检查Bundle URL的配置',
);
}
function setLocalHashInfo(hash, info) {
function setLocalHashInfo(hash: string, info: Record<string, any>) {
PushyModule.setLocalHashInfo(hash, JSON.stringify(info));
}
async function getLocalHashInfo(hash) {
async function getLocalHashInfo(hash: string) {
return JSON.parse(await PushyModule.getLocalHashInfo(hash));
}
export async function getCurrentVersionInfo() {
export async function getCurrentVersionInfo(): Promise<{
name?: string;
description?: string;
metaInfo?: string;
}> {
return currentVersion ? (await getLocalHashInfo(currentVersion)) || {} : {};
}
@@ -64,34 +73,50 @@ if (!uuid) {
PushyModule.setUuid(uuid);
}
function logger(text) {
console.log(`Pushy: ${text}`);
function logger(...args: string[]) {
console.log('Pushy: ', ...args);
}
function report(hash, type) {
logger(type);
fetch(getReportUrl(), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
hash,
type,
const noop = () => {};
let reporter: UpdateEventsListener = noop;
export function onEvents(customReporter: UpdateEventsListener) {
reporter = customReporter;
if (isRolledBack) {
report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
logger(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo,
packageVersion,
buildTime,
}),
}).catch((_e) => {});
message,
...data,
},
});
}
logger('uuid: ' + uuid);
if (isRolledBack) {
report(rolledBackVersion, 'rollback');
}
export const cInfo = {
pushy: require('../package.json').version,
rn: RNVersion,
@@ -106,7 +131,7 @@ function assertRelease() {
}
let checkingThrottling = false;
export async function checkUpdate(APPKEY, isRetry) {
export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
assertRelease();
if (checkingThrottling) {
logger('repeated checking, ignored');
@@ -117,16 +142,14 @@ export async function checkUpdate(APPKEY, isRetry) {
checkingThrottling = false;
}, 3000);
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
throw new Error(
`热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
return report({
type: 'errorChecking',
message: `热更新已暂停,原因:${blockUpdate.reason}。请在"${new Date(
blockUpdate.until * 1000,
).toLocaleString()}"`,
);
});
}
if (typeof APPKEY !== 'string') {
throw new Error('未检查到合法的APPKEY请查看update.json文件是否正确生成');
}
logger('checking update');
report({ type: 'checking' });
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), {
@@ -144,7 +167,10 @@ export async function checkUpdate(APPKEY, isRetry) {
});
} catch (e) {
if (isRetry) {
throw new Error('无法连接更新服务器,请检查网络连接后重试');
return report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
}
await tryBackupEndpoints();
return checkUpdate(APPKEY, true);
@@ -153,13 +179,15 @@ export async function checkUpdate(APPKEY, isRetry) {
checkOperation(result.op);
if (resp.status !== 200) {
throw new Error(result.message);
return report({ type: 'errorChecking', message: result.message });
}
return result;
}
function checkOperation(op) {
function checkOperation(
op: { type: string; reason: string; duration: number }[],
) {
if (!Array.isArray(op)) {
return;
}
@@ -175,8 +203,13 @@ function checkOperation(op) {
}
let downloadingThrottling = false;
let downloadedHash;
export async function downloadUpdate(options, eventListeners) {
let downloadedHash: string;
export async function downloadUpdate(
options: UpdateAvailableResult,
eventListeners?: {
onDownloadProgress?: (data: ProgressData) => void;
},
) {
assertRelease();
if (!options.update) {
return;
@@ -212,6 +245,7 @@ export async function downloadUpdate(options, eventListeners) {
}
}
let succeeded = false;
report({ type: 'downloading' });
if (options.diffUrl) {
logger('downloading diff');
try {
@@ -251,8 +285,7 @@ export async function downloadUpdate(options, eventListeners) {
}
progressHandler && progressHandler.remove();
if (!succeeded) {
report(options.hash, 'error');
throw new Error('all update attempts failed');
return report({ type: 'errorUpdate', data: { newVersion: options.hash } });
}
setLocalHashInfo(options.hash, {
name: options.name,
@@ -263,7 +296,7 @@ export async function downloadUpdate(options, eventListeners) {
return options.hash;
}
function assertHash(hash) {
function assertHash(hash: string) {
if (!downloadedHash) {
logger(`no downloaded hash`);
return;
@@ -275,7 +308,7 @@ function assertHash(hash) {
return true;
}
export function switchVersion(hash) {
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersion: ' + hash);
@@ -283,7 +316,7 @@ export function switchVersion(hash) {
}
}
export function switchVersionLater(hash) {
export function switchVersionLater(hash: string) {
assertRelease();
if (assertHash(hash)) {
logger('switchVersionLater: ' + hash);
@@ -300,21 +333,30 @@ export function markSuccess() {
}
marked = true;
PushyModule.markSuccess();
report(currentVersion, 'success');
report({ type: 'markSuccess' });
}
export async function downloadAndInstallApk({ url, onDownloadProgress }) {
logger('downloadAndInstallApk');
if (Platform.OS === 'android' && Platform.Version <= 23) {
export async function downloadAndInstallApk({
url,
onDownloadProgress,
}: {
url: string;
onDownloadProgress?: (data: ProgressData) => void;
}) {
if (Platform.OS !== 'android') {
return;
}
report({ type: 'downloadingApk' });
if (Platform.Version <= 23) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return;
return report({ type: 'rejectStoragePermission' });
}
} catch (err) {
console.warn(err);
return report({ type: 'errorStoragePermission' });
}
}
let hash = Date.now().toString();
@@ -322,7 +364,7 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
if (onDownloadProgress) {
progressHandler = eventEmitter.addListener(
'RCTPushyDownloadProgress',
(progressData) => {
(progressData: ProgressData) => {
if (progressData.hash === hash) {
onDownloadProgress(progressData);
}
@@ -333,6 +375,8 @@ export async function downloadAndInstallApk({ url, onDownloadProgress }) {
url,
target: 'update.apk',
hash,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
});
progressHandler && progressHandler.remove();
}

View File

@@ -1,5 +1,11 @@
import React, { Component } from 'react';
import { Platform, Alert, Linking, AppState } from 'react-native';
import React, { PureComponent, ComponentType } from 'react';
import {
Platform,
Alert,
Linking,
AppState,
NativeEventSubscription,
} from 'react-native';
import {
isFirstTime,
@@ -10,16 +16,25 @@ import {
switchVersionLater,
markSuccess,
downloadAndInstallApk,
onEvents,
} from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(WrappedComponent, options = {}) {
const { appKey } = options;
export function simpleUpdate(
WrappedComponent: ComponentType,
options: { appKey?: string; onEvents?: UpdateEventsListener } = {},
) {
const { appKey, onEvents: eventListeners } = options;
if (!appKey) {
throw new Error('appKey is required for simpleUpdate()');
}
if (typeof eventListeners === 'function') {
onEvents(eventListeners);
}
return __DEV__
? WrappedComponent
: class AppUpdate extends Component {
: class AppUpdate extends PureComponent {
stateListener: NativeEventSubscription;
componentDidMount() {
if (isRolledBack) {
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
@@ -70,7 +85,7 @@ export function simpleUpdate(WrappedComponent, options = {}) {
checkUpdate = async () => {
let info;
try {
info = await checkUpdate(appKey);
info = await checkUpdate(appKey!);
} catch (err) {
Alert.alert('更新检查失败', err.message);
return;

70
lib/type.ts Normal file
View File

@@ -0,0 +1,70 @@
export interface ExpiredResult {
upToDate?: false;
expired: true;
downloadUrl: string;
}
export interface UpTodateResult {
expired?: false;
upToDate: true;
paused?: 'app' | 'package';
}
export interface UpdateAvailableResult {
expired?: false;
upToDate?: false;
update: true;
name: string; // version name
hash: string;
description: string;
metaInfo: string;
pdiffUrl: string;
diffUrl?: string;
updateUrl?: string;
}
export type CheckResult =
| ExpiredResult
| UpTodateResult
| UpdateAvailableResult;
export interface ProgressData {
hash: string;
received: number;
total: number;
}
export type EventType =
| 'rollback'
| 'errorChecking'
| 'checking'
| 'downloading'
| 'errorUpdate'
| 'markSuccess'
| 'downloadingApk'
| 'rejectStoragePermission'
| 'errorStoragePermission'
| 'errowDownloadAndInstallApk';
export interface EventData {
currentVersion: string;
cInfo: {
pushy: string;
rn: string;
os: string;
uuid: string;
};
packageVersion: string;
buildTime: number;
message?: string;
rolledBackVersion?: string;
newVersion?: string;
[key: string]: any;
}
export type UpdateEventsListener = ({
type,
data,
}: {
type: EventType;
data: EventData;
}) => void;

View File

@@ -1,8 +1,8 @@
{
"name": "react-native-update",
"version": "9.0.0-beta.0",
"version": "9.0.0-beta.3",
"description": "react-native hot update",
"main": "lib/index.js",
"main": "lib/index.ts",
"scripts": {
"prepublish": "yarn submodule",
"submodule": "git submodule update --init --recursive",

View File

@@ -1,8 +1,7 @@
require 'json'
package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
folly_version = '2021.06.28.00-v2'
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'
Pod::Spec.new do |s|
s.name = package['name']
s.version = package['version']
@@ -41,18 +40,5 @@ Pod::Spec.new do |s|
'android/jni/lzma/C/Lzma2Dec.{h,c}']
ss.private_header_files = 'ios/RCTPushy/HDiffPatch/**/*.h'
end
# This guard prevent to install the dependencies when we run `pod install` in the old architecture.
if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
s.pod_target_xcconfig = {
"HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
"CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
}
s.dependency "React-Codegen"
s.dependency "RCT-Folly", folly_version
s.dependency "RCTRequired"
s.dependency "RCTTypeSafety"
s.dependency "ReactCommon/turbomodule/core"
end
install_modules_dependencies(s)
end