ldc-com-app/ComApp/src/App/Views/SyncScreen.js

337 lines
11 KiB
JavaScript
Raw Normal View History

2022-10-05 18:03:52 +02:00
import React from 'react';
import { View, Button, Alert, Text } from 'react-native';
// Redux
import { connect } from 'react-redux';
2022-12-28 17:53:43 +01:00
import { initDirectories } from '../Store/Actions/directories';
import { initContact } from '../Store/Actions/contacts';
2022-10-05 18:03:52 +02:00
// Style
import styles from '../../Resources/Styles/SyncStyle';
// Translations
import i18n from "../../I18n";
// Controller
import SyncController from '../Controllers/SyncController';
// Progress
import * as Progress from 'react-native-progress';
// Database
2022-10-06 16:25:15 +02:00
import { User, Contact, Directory, Document } from '../../Database';
// FileSytem
import * as FileSystem from 'expo-file-system';
2022-10-05 18:03:52 +02:00
function mapStateToProps(state) {
return {
syncVersion: state.app.syncVersion,
currentUser: state.app.currentUser,
2022-12-28 16:32:30 +01:00
locale: state.locale.locale,
2022-12-30 16:44:51 +01:00
mainColor: state.app.mainColor
2022-10-05 18:03:52 +02:00
};
}
2022-12-28 16:32:30 +01:00
const mapDispatchToProps = dispatch => {
return {
2022-12-28 17:53:43 +01:00
init: () => dispatch({ type: 'INIT' }),
2022-12-30 16:44:51 +01:00
initUsers: () => dispatch({ type: 'INIT_USERS' }),
2022-12-28 17:53:43 +01:00
initDirectories: (lang, user) => dispatch(initDirectories(lang, user)),
initContact: currentUser => dispatch(initContact(currentUser)),
2022-12-30 16:44:51 +01:00
initBtns: () => dispatch({ type: 'INIT_HOME_BTNS' }),
2022-12-28 16:32:30 +01:00
updateVersion: version => dispatch({
type: 'UPDATE_VERSION',
data: version,
}),
updateShowIsActive: value => dispatch({
type: 'UPDATE_SHOW_IS_ACTIVE',
data: value,
})
};
};
2022-10-05 18:03:52 +02:00
class SyncScreen extends React.Component {
state = {
progress: 0,
txtStep: '',
downloadProgress: 0,
downloadingFile: false,
processing: false,
2022-12-30 16:44:51 +01:00
newApp: false,
forced: false
2022-10-05 18:03:52 +02:00
};
2022-10-07 18:27:54 +02:00
componentDidMount() {
const { forceSync } = this.props.route.params;
if (forceSync === true) {
2022-12-30 16:44:51 +01:00
this.setState({ forced: true });
2022-10-07 18:27:54 +02:00
this.sync();
}
}
2022-10-05 18:03:52 +02:00
render() {
const fileProgress = this.fileProgress();
return (
<View style={styles.container}>
<Progress.Circle
size={250}
progress={this.state.progress}
showsText={true}
2022-12-30 10:02:07 +01:00
color={this.props.mainColor}
2022-10-05 18:03:52 +02:00
/>
<View style={styles.btnWrapper}>
<Button
disabled={this.state.processing}
2022-12-30 10:02:07 +01:00
color={this.props.mainColor}
2022-10-05 18:03:52 +02:00
title={i18n.t('sync_s.start_sync')}
onPress={() => this.sync()}
/>
</View>
<View style={styles.btnWrapper}>
<Text>
{this.state.txtStep} {fileProgress}
</Text>
</View>
</View>
);
}
async sync() {
2023-01-04 10:31:56 +01:00
const isConnected = await SyncController.checkConnection().then(state => {
//console.log(state.isConnected)
return state.isConnected
}).catch(error => {
//console.log(error);
return false;
});
if (!isConnected) {
2022-10-06 16:25:15 +02:00
Alert.alert(
i18n.t('global.warning'),
i18n.t('error.must_be_connected_internet_sync')
);
return;
}
this.setState({ processing: true });
// getVersion
const resVersion = await SyncController.getVersion().then(res => {
return res.data;
}).catch(error => {
console.log(error);
Alert.alert(
i18n.t('error.error'),
i18n.t('error.error_has_occurred')
);
});
2022-12-28 16:32:30 +01:00
this.props.updateVersion(resVersion.version);
this.props.updateShowIsActive(resVersion.ShowIsActive);
2022-10-06 16:25:15 +02:00
this.setState({ newApp: resVersion.newApp });
// getUsers
this.setState({ txtStep: i18n.t('sync_s.updating_users') + '...' });
const resUsers = await SyncController.getUsers().then(res => {
User.clear();
return res.data;
}).catch(error => {
console.log(error);
Alert.alert(
i18n.t('error.error'),
i18n.t('error.error_has_occurred')
);
});
resUsers.forEach(user => {
User.add(user);
});
// getContacts
this.setState({ progress: 0.1, txtStep: i18n.t('sync_s.updating_contacts') + '...' });
2022-12-29 10:32:28 +01:00
const resContacts = await SyncController.getContacts(this.props.currentUser.id).then(res => {
2022-10-06 16:25:15 +02:00
Contact.clear();
return res.data;
}).catch(error => {
console.log(error);
Alert.alert(
i18n.t('error.error'),
i18n.t('error.error_has_occurred')
);
});
resContacts.forEach(contact => {
Contact.add(contact);
});
//sendBrochures
this.setState({ progress: 0.2, txtStep: i18n.t('sync_s.sending_flyers') + '...' });
await SyncController.sendBrochures();
//getDirectories
this.setState({ progress: 0.3, txtStep: i18n.t('sync_s.updating_folders') + '...' });
const resDirectories = await SyncController.getDirectories().then(res => {
Directory.clear();
return res.data;
}).catch(error => {
console.log(error);
Alert.alert(
i18n.t('error.error'),
i18n.t('error.error_has_occurred')
);
});
resDirectories.forEach(dir => {
Directory.add(dir);
});
2022-10-06 16:25:15 +02:00
// getDocuments
this.setState({ progress: 0.4, txtStep: i18n.t('sync_s.updating_docs') + '...' });
const resDocuments = await SyncController.getDocuments().then(res => {
return res.data;
}).catch(error => {
console.log(error);
Alert.alert(
i18n.t('error.error'),
i18n.t('error.error_has_occurred')
);
});
const toDelete = Document.clear(resDocuments);
resDocuments.forEach(document => {
Document.update(document);
});
2023-01-02 14:47:07 +01:00
this.downloadDocuments(Document.getAll(), toDelete);
2022-10-05 18:03:52 +02:00
// End
this.setState({ txtStep: i18n.t('sync_s.update_completed') + '.', processing: false });
}
fileProgress() {
if (this.state.downloadingFile === true) {
return this.state.downloadProgress + ' %';
}
}
2022-10-06 16:25:15 +02:00
downloadDocuments(docs, toDelete) {
const version = this.props.syncVersion;
this.getToDL(docs, 0).then(toDownload => {
if (toDownload.length > 0) {
this.setState({ progress: 0.5 });
const docProgress = 0.5 / toDownload.length;
this.download(toDownload, docProgress, 0).then(status => {
if (status === true) {
this.deleteFile(toDelete, 0).then(status => {
this.finishSync(version);
});
} else {
this.setState({ txtStep: i18n.t('error.error_has_occurred') + '.' });
}
});
} else {
this.deleteFile(toDelete, 0).then(status => {
this.setState({ progress: 1 });
this.finishSync(version);
});
}
});
}
async getToDL(docs, i, toDL = []) {
if (docs.length < 1)
return toDL;
const item = docs[i];
const { exists, modificationTime } = await FileSystem.getInfoAsync(FileSystem.documentDirectory + item.uuid + '.' + item.type);
if (exists === false) {
toDL.push(item);
} else {
if (modificationTime.toString() !== item.updated_at) {
toDL.push(item);
}
}
if (i < docs.length - 1) {
return this.getToDL(docs, i + 1, toDL);
}
return toDL;
}
async deleteFile(docs, i) {
if (docs.length > 0) {
const file = docs[i];
await FileSystem.deleteAsync(FileSystem.documentDirectory + file.uuid + '.' + file.type, { idempotent: true });
if (i < docs.length - 1) {
return this.deleteFile(docs, i + 1);
}
}
return true;
}
callback(downloadProgress) {
let progress =
(downloadProgress.totalBytesWritten /
downloadProgress.totalBytesExpectedToWrite) *
100;
progress = Math.round(progress);
progress = progress.toString();
this.setState({
downloadProgress: progress,
});
}
downloadResumable(url, uuid, type) {
return FileSystem.createDownloadResumable(
url,
FileSystem.documentDirectory + uuid + '.' + type,
{},
this.callback.bind(this),
);
}
async download(documents, progress, i) {
if (this.state.downloadingFile === false) {
this.setState({ downloadingFile: true });
}
2023-01-02 15:31:47 +01:00
const endpoint = SyncController.getUrlBo() + '/storage/docs/'
2022-10-06 16:25:15 +02:00
const doc = documents[i];
this.setState({
txtStep:
i18n.t('sync_s.download') + ' : ' +
doc.title +
' (' +
doc.type.toUpperCase() +
') ...',
});
try {
2023-01-02 14:47:07 +01:00
await this.downloadResumable(
2022-10-06 16:25:15 +02:00
endpoint + doc.uuid + "." + doc.type,
doc.uuid,
doc.type,
).downloadAsync();
const { modificationTime } = await FileSystem.getInfoAsync(FileSystem.documentDirectory + doc.uuid + '.' + doc.type);
SyncController.updateLastModificationDoc(doc.id, modificationTime);
//console.log('Finished downloading to ', uri);
this.setState({ progress: this.state.progress + progress });
if (i < documents.length - 1) {
return this.download(documents, progress, i + 1);
}
this.setState({ downloadingFile: false });
return true;
} catch (e) {
console.error(e);
return false;
}
}
2023-01-02 14:47:07 +01:00
finishSync(version) {
2022-12-28 17:53:43 +01:00
this.props.init();
2022-12-30 16:44:51 +01:00
this.props.initUsers();
2022-12-28 17:53:43 +01:00
this.props.initContact(this.props.currentUser);
2022-12-30 16:44:51 +01:00
this.props.initDirectories(this.props.locale.value, this.props.currentUser);
this.props.initBtns();
if (this.state.forced) {
SyncController.setInstalled();
}
2022-10-06 16:25:15 +02:00
SyncController.updateVersion(version);
this.setState({ txtStep: i18n.t('sync_s.update_completed') + '.', processing: false });
if (this.state.newApp === true) {
const appUUID = '1f6eda31-1f6d-49fe-aa81-4f0aece0f7ca';
const url = 'https://store.ldc.fr' + '/app/' + appUUID;
Alert.alert(
'LDC Store',
i18n.t('sync_s.new_app_version'),
[
{
text: i18n.t('global.cancel'),
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{ text: i18n.t('sync_s.open_store'), onPress: () => Linking.openURL(url).catch((err) => console.error('An error occurred', err)) },
],
{ cancelable: false },
);
}
}
2022-10-05 18:03:52 +02:00
}
2022-12-28 16:32:30 +01:00
export default connect(mapStateToProps, mapDispatchToProps)(SyncScreen);