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

Compare commits

...

19 Commits

Author SHA1 Message Date
sunnylqm
22c4b01ead v10.2.4 2024-03-07 18:10:16 +08:00
sunnylqm
f655a1d954 fix: avoid double check when init 2024-03-07 18:09:55 +08:00
sunnylqm
2bdc64ba1b v10.2.3 2024-03-07 17:58:30 +08:00
sunnylqm
f5242017b9 fix: ignore checkupdate in dev env 2024-03-07 17:58:03 +08:00
sunnylqm
42e2051290 fix: add timeout 2024-03-04 12:30:00 +08:00
sunnylqm
a66f354c3b v10.2.1 2024-03-03 08:50:19 +08:00
sunnylqm
592e13b77b return null if error 2024-03-03 08:49:46 +08:00
sunnylqm
2845a4302a v10.2.0 2024-03-02 12:25:11 +08:00
sunnylqm
84ef668102 feat: test urls 2024-03-02 12:24:41 +08:00
sunnylqm
c63e1501fe v10.1.3 2024-02-25 22:24:35 +08:00
sunnylqm
45bfa2560e feat: add getCurrentVersionInfo 2024-02-25 22:23:46 +08:00
sunnylqm
ab9c40bf2e v10.1.2 2024-02-25 00:05:14 +08:00
sunnylqm
d184beabaf fix: type 2024-02-25 00:04:55 +08:00
sunnylqm
68a6235145 v10.1.1 2024-02-25 00:03:58 +08:00
sunnylqm
a98a48d665 fix: type 2024-02-25 00:03:35 +08:00
sunnylqm
4bf004a274 v10.1.0 2024-02-24 11:37:41 +08:00
sunnylqm
f01716bcb2 feat: add logger 2024-02-24 11:36:58 +08:00
sunnylqm
4f9e1495c8 v10.0.2 2024-02-19 11:42:17 +08:00
sunnylqm
9c06bac91b fix: dead loop 2024-02-19 11:41:17 +08:00
9 changed files with 130 additions and 81 deletions

View File

@@ -18,7 +18,7 @@
"react-native": "0.69.8",
"react-native-paper": "^5.12.1",
"react-native-safe-area-context": "^4.8.2",
"react-native-update": "^10.0.0-beta.3",
"react-native-update": "^10.0.2",
"react-native-vector-icons": "^10.0.3"
},
"devDependencies": {

View File

@@ -6231,10 +6231,10 @@ react-native-safe-area-context@^4.8.2:
resolved "https://registry.yarnpkg.com/react-native-safe-area-context/-/react-native-safe-area-context-4.8.2.tgz#e6b3d8acf3c6afcb4b5db03a97f9c37df7668f65"
integrity sha512-ffUOv8BJQ6RqO3nLml5gxJ6ab3EestPiyWekxdzO/1MQ7NF8fW1Mzh1C5QE9yq573Xefnc7FuzGXjtesZGv7cQ==
react-native-update@^10.0.0-beta.3:
version "10.0.0-beta.3"
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.0-beta.3.tgz#cad099ebb40ff04b31ba2df13930517039e4fae3"
integrity sha512-Ak1ylgHbOUeaNsq3ItZGRenqqAwYKSTlB6T4sBn4PPNGaMmIMt6uIKKWrQqcNyc9WEy9LlFM6kSqQXBQdaVatw==
react-native-update@^10.0.2:
version "10.0.2"
resolved "https://registry.yarnpkg.com/react-native-update/-/react-native-update-10.0.2.tgz#2bb01ab6e41e72bbbb535cebd34083b1fed69eb0"
integrity sha512-XkEPmTC3X6FV1eXq6uDyjfhXpAaug0HI48Mm+PkbMlXcgFjTrOmtuq7yuvemS2nPG2pwnrYQuGs0A6tE2aoRBA==
dependencies:
nanoid "^3.3.3"

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "10.0.1",
"version": "10.2.4",
"description": "react-native hot update",
"main": "src/index.ts",
"scripts": {

View File

@@ -1,5 +1,5 @@
import { CheckResult, PushyOptions, ProgressData } from './type';
import { assertRelease, log } from './utils';
import { CheckResult, PushyOptions, ProgressData, EventType } from './type';
import { assertRelease, log, testUrls } from './utils';
import {
EmitterSubscription,
PermissionsAndroid,
@@ -12,9 +12,9 @@ import {
pushyNativeEventEmitter,
currentVersion,
packageVersion,
report,
rolledBackVersion,
setLocalHashInfo,
isRolledBack,
} from './core';
const defaultServer = {
@@ -25,6 +25,8 @@ const defaultServer = {
};
const empty = {};
const noop = () => {};
export class Pushy {
options: PushyOptions = {
appKey: '',
@@ -32,10 +34,11 @@ export class Pushy {
autoMarkSuccess: true,
useAlert: true,
strategy: 'both',
logger: noop,
};
lastChecking: number;
lastResult: CheckResult;
lastRespJson?: Promise<any>;
progressHandlers: Record<string, EmitterSubscription> = {};
downloadedHash: string;
@@ -55,10 +58,45 @@ export class Pushy {
for (const [key, value] of Object.entries(options)) {
if (value !== undefined) {
this.options[key] = value;
if (key === 'logger') {
if (isRolledBack) {
this.report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
}
}
};
report = ({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) => {
log(type + ' ' + message);
const { logger = noop, appKey } = this.options;
logger({
type,
data: {
appKey,
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
};
getCheckUrl = (endpoint: string = this.options.server!.main) => {
return `${endpoint}/checkUpdate/${this.options.appKey}`;
};
@@ -79,7 +117,7 @@ export class Pushy {
}
this.marked = true;
PushyModule.markSuccess();
report({ type: 'markSuccess' });
this.report({ type: 'markSuccess' });
};
switchVersion = (hash: string) => {
assertRelease();
@@ -101,14 +139,14 @@ export class Pushy {
assertRelease();
const now = Date.now();
if (
this.lastResult &&
this.lastRespJson &&
this.lastChecking &&
now - this.lastChecking < 1000 * 5
) {
return this.lastResult;
return await this.lastRespJson;
}
this.lastChecking = now;
report({ type: 'checking' });
this.report({ type: 'checking' });
const fetchPayload = {
method: 'POST',
headers: {
@@ -126,7 +164,7 @@ export class Pushy {
try {
resp = await fetch(this.getCheckUrl(), fetchPayload);
} catch (e) {
report({
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Trying backup endpoints.',
});
@@ -142,18 +180,18 @@ export class Pushy {
}
}
if (!resp) {
report({
this.report({
type: 'errorChecking',
message: 'Can not connect to update server. Please check your network.',
});
return this.lastResult || empty;
return this.lastRespJson ? await this.lastRespJson : empty;
}
const result: CheckResult = await resp.json();
this.lastRespJson = resp.json();
this.lastResult = result;
const result: CheckResult = await this.lastRespJson;
if (resp.status !== 200) {
report({
this.report({
type: 'errorChecking',
message: result.message,
});
@@ -187,8 +225,18 @@ export class Pushy {
onDownloadProgress?: (data: ProgressData) => void,
) => {
assertRelease();
const { hash, diffUrl, pdiffUrl, updateUrl, name, description, metaInfo } =
info;
const {
hash,
diffUrl: _diffUrl,
diffUrls,
pdiffUrl: _pdiffUrl,
pdiffUrls,
updateUrl: _updateUrl,
updateUrls,
name,
description,
metaInfo,
} = info;
if (!info.update || !hash) {
return;
}
@@ -214,7 +262,8 @@ export class Pushy {
);
}
let succeeded = false;
report({ type: 'downloading' });
this.report({ type: 'downloading' });
const diffUrl = (await testUrls(diffUrls)) || _diffUrl;
if (diffUrl) {
log('downloading diff');
try {
@@ -228,6 +277,7 @@ export class Pushy {
log(`diff error: ${e.message}, try pdiff`);
}
}
const pdiffUrl = (await testUrls(pdiffUrls)) || _pdiffUrl;
if (!succeeded && pdiffUrl) {
log('downloading pdiff');
try {
@@ -240,6 +290,7 @@ export class Pushy {
log(`pdiff error: ${e.message}, try full patch`);
}
}
const updateUrl = (await testUrls(updateUrls)) || _updateUrl;
if (!succeeded && updateUrl) {
log('downloading full patch');
try {
@@ -257,7 +308,7 @@ export class Pushy {
delete this.progressHandlers[hash];
}
if (!succeeded) {
return report({
return this.report({
type: 'errorUpdate',
data: { newVersion: hash },
});
@@ -278,17 +329,17 @@ export class Pushy {
if (Platform.OS !== 'android') {
return;
}
report({ type: 'downloadingApk' });
this.report({ type: 'downloadingApk' });
if (Platform.Version <= 23) {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
return report({ type: 'rejectStoragePermission' });
return this.report({ type: 'rejectStoragePermission' });
}
} catch (err) {
return report({ type: 'errorStoragePermission' });
return this.report({ type: 'errorStoragePermission' });
}
}
const progressKey = 'downloadingApk';
@@ -307,7 +358,7 @@ export class Pushy {
target: 'update.apk',
hash: progressKey,
}).catch(() => {
report({ type: 'errowDownloadAndInstallApk' });
this.report({ type: 'errowDownloadAndInstallApk' });
});
if (this.progressHandlers[progressKey]) {
this.progressHandlers[progressKey].remove();

View File

@@ -2,29 +2,35 @@ import { createContext, useContext } from 'react';
import { CheckResult, ProgressData } from './type';
import { Pushy } from './client';
const empty = {};
const noop = () => {};
const asyncNoop = () => Promise.resolve();
export const defaultContext = {
checkUpdate: () => Promise.resolve(empty),
checkUpdate: asyncNoop,
switchVersion: noop,
switchVersionLater: noop,
markSuccess: noop,
dismissError: noop,
downloadUpdate: noop,
downloadAndInstallApk: noop,
downloadUpdate: asyncNoop,
downloadAndInstallApk: asyncNoop,
getCurrentVersionInfo: () => Promise.resolve({}),
currentHash: '',
packageVersion: '',
};
export const PushyContext = createContext<{
checkUpdate: () => void;
checkUpdate: () => Promise<void>;
switchVersion: () => void;
switchVersionLater: () => void;
markSuccess: () => void;
dismissError: () => void;
downloadUpdate: () => void;
downloadAndInstallApk: (url: string) => void;
downloadUpdate: () => Promise<void>;
downloadAndInstallApk: (url: string) => Promise<void>;
getCurrentVersionInfo: () => Promise<{
name?: string;
description?: string;
metaInfo?: string;
}>;
currentHash: string;
packageVersion: string;
client?: Pushy;

View File

@@ -1,5 +1,4 @@
import { NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { EventType, UpdateEventsLogger } from './type';
import { log } from './utils';
const {
version: v,
@@ -58,44 +57,6 @@ if (!uuid) {
PushyModule.setUuid(uuid);
}
const noop = () => {};
let reporter: UpdateEventsLogger = noop;
export function onPushyEvents(customReporter: UpdateEventsLogger) {
reporter = customReporter;
if (isRolledBack) {
report({
type: 'rollback',
data: {
rolledBackVersion,
},
});
}
}
export function report({
type,
message = '',
data = {},
}: {
type: EventType;
message?: string;
data?: Record<string, string | number>;
}) {
log(type + ' ' + message);
reporter({
type,
data: {
currentVersion,
cInfo,
packageVersion,
buildTime,
message,
...data,
},
});
}
log('uuid: ' + uuid);
export const cInfo = {

View File

@@ -13,7 +13,12 @@ import {
Linking,
} from 'react-native';
import { Pushy } from './client';
import { currentVersion, isFirstTime, packageVersion } from './core';
import {
currentVersion,
isFirstTime,
packageVersion,
getCurrentVersionInfo,
} from './core';
import { CheckResult, ProgressData } from './type';
import { PushyContext } from './context';
@@ -31,10 +36,8 @@ export const PushyProvider = ({
const [lastError, setLastError] = useState<Error>();
const dismissError = useCallback(() => {
if (lastError) {
setLastError(undefined);
}
}, [lastError]);
setLastError(undefined);
}, []);
const showAlert = useCallback(
(...args: Parameters<typeof Alert.alert>) => {
@@ -90,9 +93,9 @@ export const PushyProvider = ({
}, [client, showAlert, updateInfo]);
const downloadAndInstallApk = useCallback(
(downloadUrl: string) => {
async (downloadUrl: string) => {
if (Platform.OS === 'android' && downloadUrl) {
client.downloadAndInstallApk(downloadUrl, setProgress);
await client.downloadAndInstallApk(downloadUrl, setProgress);
}
},
[client],
@@ -145,6 +148,10 @@ export const PushyProvider = ({
const markSuccess = client.markSuccess;
useEffect(() => {
if (__DEV__) {
console.info('检测到在DEV环境不会进行热更新检查');
return;
}
const { strategy, dismissErrorAfter, autoMarkSuccess } = options;
if (isFirstTime && autoMarkSuccess) {
markSuccess();
@@ -190,6 +197,7 @@ export const PushyProvider = ({
currentHash: currentVersion,
progress,
downloadAndInstallApk,
getCurrentVersionInfo,
}}
>
{children}

View File

@@ -8,8 +8,11 @@ export interface CheckResult {
description?: string;
metaInfo?: string;
pdiffUrl?: string;
pdiffUrls?: string[];
diffUrl?: string;
diffUrls?: string[];
updateUrl?: string;
updateUrls?: string[];
paused?: 'app' | 'package';
message?: string;
}

View File

@@ -7,3 +7,23 @@ export function assertRelease() {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
const ping = async (url: string) =>
Promise.race([
fetch(url, {
method: 'HEAD',
redirect: 'follow',
}).then(({ status }) => status === 200),
new Promise<false>((r) => setTimeout(() => r(false), 2000)),
]);
const canUseGoogle = ping('https://www.google.com');
export const testUrls = async (urls?: string[]) => {
if (!urls?.length || (await canUseGoogle)) {
return null;
}
return Promise.race(urls.map((url) => ping(url).then(() => url))).catch(
() => null,
);
};