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

Compare commits

..

11 Commits

Author SHA1 Message Date
sunnylqm
3e02ff6099 v10.13.2 2024-08-26 18:57:13 +08:00
sunnylqm
462a342172 v10.13.1 2024-08-26 18:54:17 +08:00
sunnylqm
94d2e18900 v10.13.0 2024-08-26 18:52:44 +08:00
sunnylqm
d000c40e0f v10.12.0 2024-08-24 15:28:27 +08:00
sunnylqm
5659c79726 v10.11.8 2024-08-21 20:02:47 +08:00
sunnylqm
b20d987473 fix marksuccess 2024-08-21 19:58:28 +08:00
sunnylqm
14c9c0b1f5 v10.11.7 2024-08-16 11:03:25 +08:00
sunnylqm
10178e1e64 chore: Update switchVersion and switchVersionLater to be async functions 2024-08-16 10:49:35 +08:00
sunnylqm
6d980a4c04 v10.11.6 2024-08-06 13:13:05 +08:00
sunnylqm
084fbf35ee fix typo 2024-08-06 13:12:32 +08:00
sunnylqm
d666e8c0f3 v10.11.5 2024-08-01 11:00:39 +08:00
8 changed files with 77 additions and 55 deletions

View File

@@ -75,7 +75,7 @@ RCT_EXPORT_MODULE(RCTPushy);
if (needClearPushyInfo) { if (needClearPushyInfo) {
[defaults setObject:nil forKey:keyPushyInfo]; [defaults setObject:nil forKey:keyPushyInfo];
[defaults setObject:@(YES) forKey:KeyPackageUpdatedMarked]; [defaults setObject:@(YES) forKey:KeyPackageUpdatedMarked];
[defaults synchronize];
// ...need clear files later // ...need clear files later
} }
else { else {
@@ -97,7 +97,7 @@ RCT_EXPORT_MODULE(RCTPushy);
newInfo[paramIsFirstTime] = @(NO); newInfo[paramIsFirstTime] = @(NO);
[defaults setObject:newInfo forKey:keyPushyInfo]; [defaults setObject:newInfo forKey:keyPushyInfo];
[defaults setObject:@(YES) forKey:keyFirstLoadMarked]; [defaults setObject:@(YES) forKey:keyFirstLoadMarked];
[defaults synchronize];
} }
NSString *downloadDir = [RCTPushy downloadDir]; NSString *downloadDir = [RCTPushy downloadDir];
@@ -137,7 +137,7 @@ RCT_EXPORT_MODULE(RCTPushy);
[defaults setObject:nil forKey:keyPushyInfo]; [defaults setObject:nil forKey:keyPushyInfo];
} }
[defaults setObject:curVersion forKey:keyRolledBackMarked]; [defaults setObject:curVersion forKey:keyRolledBackMarked];
[defaults synchronize];
return lastVersion; return lastVersion;
} }
@@ -176,7 +176,7 @@ RCT_EXPORT_MODULE(RCTPushy);
[defaults setObject:nil forKey:KeyPackageUpdatedMarked]; [defaults setObject:nil forKey:KeyPackageUpdatedMarked];
[self clearInvalidFiles]; [self clearInvalidFiles];
} }
[defaults synchronize];
return ret; return ret;
} }
@@ -196,7 +196,7 @@ RCT_EXPORT_METHOD(setUuid:(NSString *)uuid resolver:(RCTPromiseResolveBlock)res
@try { @try {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:uuid forKey:keyUuid]; [defaults setObject:uuid forKey:keyUuid];
[defaults synchronize];
resolve(@true); resolve(@true);
} }
@catch (NSException *exception) { @catch (NSException *exception) {
@@ -214,7 +214,7 @@ RCT_EXPORT_METHOD(setLocalHashInfo:(NSString *)hash
if (object && [object isKindOfClass:[NSDictionary class]]) { if (object && [object isKindOfClass:[NSDictionary class]]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:value forKey:[keyHashInfo stringByAppendingString:hash]]; [defaults setObject:value forKey:[keyHashInfo stringByAppendingString:hash]];
[defaults synchronize];
resolve(@true); resolve(@true);
} else { } else {
reject(@"json格式校验报错", nil, nil); reject(@"json格式校验报错", nil, nil);
@@ -295,7 +295,7 @@ RCT_EXPORT_METHOD(setNeedUpdate:(NSDictionary *)options
newInfo[paramPackageVersion] = [RCTPushy packageVersion]; newInfo[paramPackageVersion] = [RCTPushy packageVersion];
[defaults setObject:newInfo forKey:keyPushyInfo]; [defaults setObject:newInfo forKey:keyPushyInfo];
[defaults synchronize];
resolve(@true); resolve(@true);
}else{ }else{
reject(@"执行报错", nil, nil); reject(@"执行报错", nil, nil);
@@ -329,8 +329,7 @@ RCT_EXPORT_METHOD(reloadUpdate:(NSDictionary *)options
} }
} }
RCT_EXPORT_METHOD(markSuccess: RCT_EXPORT_METHOD(markSuccess:(RCTPromiseResolveBlock)resolve
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject) rejecter:(RCTPromiseRejectBlock)reject)
{ {
@@ -347,7 +346,7 @@ RCT_EXPORT_METHOD(markSuccess:
[pushyInfo removeObjectForKey:[keyHashInfo stringByAppendingString:lastVersion]]; [pushyInfo removeObjectForKey:[keyHashInfo stringByAppendingString:lastVersion]];
} }
[defaults setObject:pushyInfo forKey:keyPushyInfo]; [defaults setObject:pushyInfo forKey:keyPushyInfo];
[defaults synchronize];
// clear other package dir // clear other package dir
[self clearInvalidFiles]; [self clearInvalidFiles];
@@ -610,7 +609,7 @@ RCT_EXPORT_METHOD(markSuccess:
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule: - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
(const facebook::react::ObjCTurboModule::InitParams &)params (const facebook::react::ObjCTurboModule::InitParams &)params
{ {
return std::make_shared<facebook::react::NativeUpdateSpecJSI>(params); return std::make_shared<facebook::react::NativePushySpecJSI>(params);
} }
#endif #endif

View File

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

View File

@@ -1,5 +1,5 @@
import { CheckResult, PushyOptions, ProgressData, EventType } from './type'; import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { log, testUrls } from './utils'; import { joinUrls, log, testUrls } from './utils';
import { EmitterSubscription, Platform } from 'react-native'; import { EmitterSubscription, Platform } from 'react-native';
import { PermissionsAndroid } from './permissions'; import { PermissionsAndroid } from './permissions';
import { import {
@@ -64,8 +64,7 @@ export class Pushy {
setOptions = (options: Partial<PushyOptions>) => { setOptions = (options: Partial<PushyOptions>) => {
for (const [key, value] of Object.entries(options)) { for (const [key, value] of Object.entries(options)) {
if (value !== undefined) { if (value !== undefined) {
// @ts-expect-error (this.options as any)[key] = value;
this.options[key] = value;
if (key === 'logger') { if (key === 'logger') {
if (isRolledBack) { if (isRolledBack) {
this.report({ this.report({
@@ -126,7 +125,7 @@ export class Pushy {
PushyModule.markSuccess(); PushyModule.markSuccess();
this.report({ type: 'markSuccess' }); this.report({ type: 'markSuccess' });
}; };
switchVersion = (hash: string) => { switchVersion = async (hash: string) => {
if (__DEV__) { if (__DEV__) {
console.warn( console.warn(
'您调用了switchVersion方法但是当前是开发环境不会进行任何操作。', '您调用了switchVersion方法但是当前是开发环境不会进行任何操作。',
@@ -136,11 +135,11 @@ export class Pushy {
if (this.assertHash(hash) && !this.applyingUpdate) { if (this.assertHash(hash) && !this.applyingUpdate) {
log('switchVersion: ' + hash); log('switchVersion: ' + hash);
this.applyingUpdate = true; this.applyingUpdate = true;
PushyModule.reloadUpdate({ hash }); return PushyModule.reloadUpdate({ hash });
} }
}; };
switchVersionLater = (hash: string) => { switchVersionLater = async (hash: string) => {
if (__DEV__) { if (__DEV__) {
console.warn( console.warn(
'您调用了switchVersionLater方法但是当前是开发环境不会进行任何操作。', '您调用了switchVersionLater方法但是当前是开发环境不会进行任何操作。',
@@ -149,7 +148,7 @@ export class Pushy {
} }
if (this.assertHash(hash)) { if (this.assertHash(hash)) {
log('switchVersionLater: ' + hash); log('switchVersionLater: ' + hash);
PushyModule.setNeedUpdate({ hash }); return PushyModule.setNeedUpdate({ hash });
} }
}; };
checkUpdate = async (extra?: Record<string, any>) => { checkUpdate = async (extra?: Record<string, any>) => {
@@ -163,6 +162,13 @@ export class Pushy {
console.warn('web 端不支持热更新检查'); console.warn('web 端不支持热更新检查');
return; return;
} }
if (
this.options.beforeCheckUpdate &&
(await this.options.beforeCheckUpdate()) === false
) {
log('beforeCheckUpdate 返回 false, 忽略检查');
return;
}
const now = Date.now(); const now = Date.now();
if ( if (
this.lastRespJson && this.lastRespJson &&
@@ -172,7 +178,6 @@ export class Pushy {
return await this.lastRespJson; return await this.lastRespJson;
} }
this.lastChecking = now; this.lastChecking = now;
this.report({ type: 'checking' });
const fetchBody = { const fetchBody = {
packageVersion, packageVersion,
hash: currentVersion, hash: currentVersion,
@@ -183,16 +188,21 @@ export class Pushy {
if (__DEV__) { if (__DEV__) {
delete fetchBody.buildTime; delete fetchBody.buildTime;
} }
const body = JSON.stringify(fetchBody);
const fetchPayload = { const fetchPayload = {
method: 'POST', method: 'POST',
headers: { headers: {
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify(fetchBody), body,
}; };
let resp; let resp;
try { try {
this.report({
type: 'checking',
message: this.options.appKey + ': ' + body,
});
resp = await fetch(this.getCheckUrl(), fetchPayload); resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e: any) { } catch (e: any) {
this.report({ this.report({
@@ -221,6 +231,8 @@ export class Pushy {
const result: CheckResult = await this.lastRespJson; const result: CheckResult = await this.lastRespJson;
log('checking result:', result);
if (resp.status !== 200) { if (resp.status !== 200) {
this.report({ this.report({
type: 'errorChecking', type: 'errorChecking',
@@ -259,16 +271,21 @@ export class Pushy {
) => { ) => {
const { const {
hash, hash,
diffUrl: _diffUrl, diff,
diffUrls, pdiff,
pdiffUrl: _pdiffUrl, full,
pdiffUrls, paths = [],
updateUrl: _updateUrl,
updateUrls,
name, name,
description, description = '',
metaInfo, metaInfo = '',
} = info; } = info;
if (
this.options.beforeDownloadUpdate &&
(await this.options.beforeDownloadUpdate(info)) === false
) {
log('beforeDownloadUpdate 返回 false, 忽略下载');
return;
}
if (!info.update || !hash) { if (!info.update || !hash) {
return; return;
} }
@@ -296,7 +313,7 @@ export class Pushy {
let succeeded = ''; let succeeded = '';
this.report({ type: 'downloading' }); this.report({ type: 'downloading' });
let lastError: any; let lastError: any;
const diffUrl = (await testUrls(diffUrls)) || _diffUrl; const diffUrl = await testUrls(joinUrls(paths, diff));
if (diffUrl) { if (diffUrl) {
log('downloading diff'); log('downloading diff');
try { try {
@@ -315,7 +332,7 @@ export class Pushy {
} }
} }
} }
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl; const pdiffUrl = await testUrls(joinUrls(paths, pdiff));
if (!succeeded && pdiffUrl) { if (!succeeded && pdiffUrl) {
log('downloading pdiff'); log('downloading pdiff');
try { try {
@@ -333,12 +350,12 @@ export class Pushy {
} }
} }
} }
const updateUrl = (await testUrls(updateUrls)) || _updateUrl; const fullUrl = await testUrls(joinUrls(paths, full));
if (!succeeded && updateUrl) { if (!succeeded && fullUrl) {
log('downloading full patch'); log('downloading full patch');
try { try {
await PushyModule.downloadFullUpdate({ await PushyModule.downloadFullUpdate({
updateUrl: updateUrl, updateUrl: fullUrl,
hash, hash,
}); });
succeeded = 'full'; succeeded = 'full';

View File

@@ -7,8 +7,8 @@ const asyncNoop = () => Promise.resolve();
export const defaultContext = { export const defaultContext = {
checkUpdate: asyncNoop, checkUpdate: asyncNoop,
switchVersion: noop, switchVersion: asyncNoop,
switchVersionLater: noop, switchVersionLater: asyncNoop,
markSuccess: noop, markSuccess: noop,
dismissError: noop, dismissError: noop,
downloadUpdate: asyncNoop, downloadUpdate: asyncNoop,
@@ -21,8 +21,8 @@ export const defaultContext = {
export const PushyContext = createContext<{ export const PushyContext = createContext<{
checkUpdate: () => Promise<void>; checkUpdate: () => Promise<void>;
switchVersion: () => void; switchVersion: () => Promise<void>;
switchVersionLater: () => void; switchVersionLater: () => Promise<void>;
markSuccess: () => void; markSuccess: () => void;
dismissError: () => void; dismissError: () => void;
downloadUpdate: () => Promise<void>; downloadUpdate: () => Promise<void>;

View File

@@ -4,9 +4,7 @@ const {
version: v, version: v,
} = require('react-native/Libraries/Core/ReactNativeVersion'); } = require('react-native/Libraries/Core/ReactNativeVersion');
const RNVersion = `${v.major}.${v.minor}.${v.patch}`; const RNVersion = `${v.major}.${v.minor}.${v.patch}`;
const isTurboModuleEnabled = const isTurboModuleEnabled = (global as any).__turboModuleProxy != null;
// @ts-expect-error
global.__turboModuleProxy != null;
export const PushyModule = export const PushyModule =
Platform.OS === 'web' Platform.OS === 'web'

View File

@@ -73,18 +73,18 @@ export const PushyProvider = ({
); );
const switchVersion = useCallback( const switchVersion = useCallback(
(info: CheckResult | undefined = updateInfoRef.current) => { async (info: CheckResult | undefined = updateInfoRef.current) => {
if (info && info.hash) { if (info && info.hash) {
client.switchVersion(info.hash); return client.switchVersion(info.hash);
} }
}, },
[client], [client],
); );
const switchVersionLater = useCallback( const switchVersionLater = useCallback(
(info: CheckResult | undefined = updateInfoRef.current) => { async (info: CheckResult | undefined = updateInfoRef.current) => {
if (info && info.hash) { if (info && info.hash) {
client.switchVersionLater(info.hash); return client.switchVersionLater(info.hash);
} }
}, },
[client], [client],
@@ -290,10 +290,9 @@ export const PushyProvider = ({
); );
const parseTestQrCode = useCallback( const parseTestQrCode = useCallback(
(code: string) => { (code: string | PushyTestPayload) => {
let payload: PushyTestPayload;
try { try {
payload = JSON.parse(code); const payload = typeof code === 'string' ? JSON.parse(code) : code;
return parseTestPayload(payload); return parseTestPayload(payload);
} catch { } catch {
return false; return false;

View File

@@ -7,12 +7,10 @@ export interface CheckResult {
hash?: string; hash?: string;
description?: string; description?: string;
metaInfo?: string; metaInfo?: string;
pdiffUrl?: string; pdiff?: string;
pdiffUrls?: string[]; diff?: string;
diffUrl?: string; full?: string;
diffUrls?: string[]; paths?: string[];
updateUrl?: string;
updateUrls?: string[];
paused?: 'app' | 'package'; paused?: 'app' | 'package';
message?: string; message?: string;
} }
@@ -81,6 +79,8 @@ export interface PushyOptions {
dismissErrorAfter?: number; dismissErrorAfter?: number;
debug?: boolean; debug?: boolean;
throwError?: boolean; throwError?: boolean;
beforeCheckUpdate?: () => Promise<boolean>;
beforeDownloadUpdate?: (info: CheckResult) => Promise<boolean>;
} }
export interface PushyTestPayload { export interface PushyTestPayload {

View File

@@ -31,9 +31,18 @@ const ping =
const canUseGoogle = ping('https://www.google.com'); const canUseGoogle = ping('https://www.google.com');
export function joinUrls(paths: string[], fileName?: string) {
if (fileName) {
return paths.map(path => 'https://' + path + '/' + fileName);
}
}
export const testUrls = async (urls?: string[]) => { export const testUrls = async (urls?: string[]) => {
if (!urls?.length || (await canUseGoogle)) { if (!urls?.length) {
return null; return null;
} }
if (await canUseGoogle) {
return urls[0];
}
return Promise.race(urls.map(ping)).catch(() => null); return Promise.race(urls.map(ping)).catch(() => null);
}; };