1
0
Code Issues Pull Requests Packages Projects Releases Wiki Activity GitHub Gitee
react-native-pushy/lib/simpleUpdate.js

121 lines
3.4 KiB
JavaScript
Raw Normal View History

2021-10-09 13:12:09 +08:00
import React, { Component } from 'react';
import { Platform, Alert, Linking, AppState } from 'react-native';
import {
isFirstTime,
isRolledBack,
checkUpdate,
downloadUpdate,
switchVersion,
switchVersionLater,
markSuccess,
downloadAndInstallApk,
} from './main';
export function simpleUpdate(WrappedComponent, options = {}) {
const { appKey } = options;
if (!appKey) {
throw new Error('appKey is required for simpleUpdate()');
}
2021-10-09 13:12:09 +08:00
return __DEV__
? WrappedComponent
: class AppUpdate extends Component {
componentDidMount() {
if (isRolledBack) {
Alert.alert('抱歉', '刚刚更新遭遇错误,已为您恢复到更新前版本');
} else if (isFirstTime) {
markSuccess();
}
this.stateListener = AppState.addEventListener(
'change',
(nextAppState) => {
if (nextAppState === 'active') {
this.checkUpdate();
}
},
);
this.checkUpdate();
}
componentWillUnmount() {
2021-11-10 22:31:23 +08:00
this.stateListener && this.stateListener.remove();
2021-10-09 13:12:09 +08:00
}
doUpdate = async (info) => {
try {
const hash = await downloadUpdate(info);
2021-11-04 16:35:34 +08:00
if (!hash) {
return;
}
2021-11-10 22:31:23 +08:00
this.stateListener && this.stateListener.remove();
2021-10-09 13:12:09 +08:00
Alert.alert('提示', '下载完毕,是否立即更新?', [
{
text: '以后再说',
style: 'cancel',
onPress: () => {
switchVersionLater(hash);
},
},
{
text: '立即更新',
style: 'default',
onPress: () => {
switchVersion(hash);
},
},
]);
} catch (err) {
Alert.alert('更新失败', err.message);
}
};
checkUpdate = async () => {
let info;
try {
info = await checkUpdate(appKey);
} catch (err) {
Alert.alert('更新检查失败', err.message);
return;
}
if (info.expired) {
Alert.alert('提示', '您的应用版本已更新,点击确定下载安装新版本', [
{
text: '确定',
onPress: () => {
if (info.downloadUrl) {
if (
Platform.OS === 'android' &&
info.downloadUrl.endsWith('.apk')
) {
downloadAndInstallApk({
url: info.downloadUrl,
});
} else {
Linking.openURL(info.downloadUrl);
}
}
},
},
]);
2021-11-04 17:52:30 +08:00
} else if (info.update) {
2021-10-09 13:12:09 +08:00
Alert.alert(
'提示',
'检查到新的版本' + info.name + ',是否下载?\n' + info.description,
[
{ text: '否', style: 'cancel' },
{
text: '是',
style: 'default',
onPress: () => {
this.doUpdate(info);
},
},
],
);
}
};
render() {
return <WrappedComponent {...this.props} />;
}
};
}