Clean synchro check + remove useless files

This commit is contained in:
Vincent BRIDIER 2023-01-02 16:27:03 +01:00
parent 34c7f1a059
commit 2c522915f5
No known key found for this signature in database
GPG key ID: 8571BFA20420D512
15 changed files with 31 additions and 1700 deletions

View file

@ -159,9 +159,7 @@ class App extends React.Component {
)}
<TouchableOpacity
onPress={() =>
navigation.navigation.navigate('SyncScreen', {
isInstalled: true,
})
navigation.navigation.navigate('SyncScreen')
}
style={{ marginRight: 25 }}>
<Icon name="sync-alt" size={20} />
@ -181,6 +179,7 @@ class App extends React.Component {
<Stack.Screen
name="SyncScreen"
component={SyncScreen}
initialParams={{ forceSync: false }}
options={(navigation, route) => ({
headerTitle: () => this.LogoTitle(navigation, i18n.t('global.synchronization'))
})}

View file

@ -130,12 +130,12 @@ class SyncController {
}
isSynced() {
const SendBrochure = SendBrochure.getAll();
const brochures = SendBrochure.getAll();
const Contacts = Contact.getAll();
if (SendBrochure !== undefined && Contacts !== undefined) {
if (brochures !== undefined && Contacts !== undefined) {
const noSynced = Contacts.filtered('synced = false');
if (SendBrochure.length > 0 || noSynced.length > 0) {
if (brochures.length > 0 || noSynced.length > 0) {
return false;
}
}
@ -193,8 +193,12 @@ class SyncController {
return false;
}
setInstalled() {
Setting.add({ key: 'installed', value: "true" });
setInstalled(remove = false) {
if (remove) {
Setting.delete('installed');
} else {
Setting.add({ key: 'installed', value: "true" });
}
}
isInstalled() {

View file

@ -8,6 +8,7 @@ const initialState = {
currentUser: {},
logged: false,
syncVersion: 0,
forceSync: false,
currentOpenedDoc: {},
ShowIsActive: 0,
HomeBtns: {},

View file

@ -44,7 +44,6 @@ class HomeScreen extends React.Component {
};
componentDidMount() {
// Si on est sur une installation
if (!SyncController.isInstalled()) {
return this.openSync();
}

View file

@ -39,7 +39,7 @@ class LoginScreen extends React.Component {
componentDidMount() {
if (SyncController.isLogged()) {
this.props.setCurrentUser();
this.props.setCurrentUser(false);
}
}
@ -102,38 +102,39 @@ class LoginScreen extends React.Component {
const lastUser = Setting.get('lastUser');
// Si on est sur une installation
if (lastUser === false || lastUser == undefined) {
return this.loginAction(user);
}
// TODO : a deplacer dans home screen
// Si on a deja une install avec une précédente connexion
if (lastUser !== false && lastUser !== undefined && lastUser.value === user.id.toString()) {
this.loginAction(user);
} else {
// Si user !== last user && last user not synced
if (lastUser.value !== user.id.toString() && !SyncController.isSynced()) {
Alert.alert(i18n.t('error.error'), i18n.t('error.tablet_not_synced_last_user'));
// Si la tablette est connectée à internet pour forcer la synchro
if (!SyncController.checkConnection()) {
Alert.alert(i18n.t('error.error'), i18n.t('error.tablet_not_connected_internet'));
return;
}
// Si user !== last user
if (lastUser.value !== user.id.toString()) {
return this.loginAction(user);
}
// Si on a deja une install
if (lastUser !== false && lastUser !== undefined) {
// Si on a une précédente connexion
if (lastUser.value === user.id.toString()) {
this.loginAction(user);
} else { // Si le user precedent est different du user courant
// Si user !== last user && last user not synced
if (!SyncController.isSynced()) {
Alert.alert(i18n.t('error.error'), i18n.t('error.tablet_not_synced_last_user'));
return;
}
// Si la tablette est connectée à internet pour forcer la synchro
if (!SyncController.checkConnection()) {
Alert.alert(i18n.t('error.error'), i18n.t('error.tablet_not_connected_internet'));
return;
}
SyncController.setInstalled(true);
this.loginAction(user, true);
}
}
}
loginAction(user, forceSync = false) {
loginAction(user) {
this.setState({ login: '', password: '' });
LoginController.login(user);
this.props.setCurrentUser();
if (forceSync === true) {
this.props.navigation.navigate('SyncScreen', { forceSync: true });
}
}
}

View file

@ -1,614 +0,0 @@
import React from 'react';
import {
View,
StyleSheet,
Button,
FlatList,
Text,
Dimensions,
TouchableOpacity,
Alert,
TextInput,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect, ReactReduxContext } from 'react-redux';
import { showMessage } from 'react-native-flash-message';
import { Overlay } from '@rneui/themed';
import Helpers from "../Controllers/Helpers";
import i18n from "../I18n";
import { Picker } from '@react-native-picker/picker';
function mapStateToProps(state) {
return {
users: state.users,
contacts: state.contacts,
documents: state.documents,
currentUser: state.currentUser,
};
}
class ContactScreen extends React.Component {
state = {
contacts: [],
sortType: 'asc',
sortField: 'name',
searchTxt: '',
showTransferContact: false,
selectedTransferUser: 0,
contactToTransfer: {},
showSendBrochure: false,
selectedDocument: -1,
sendDocumentList: [],
selectedSendBrochureEmail: -1,
tmpSendBrochureEmail: '',
tmpSendBrochureSubject: '',
tmpSendBrochureMessage: '',
sortedDocuments: [],
sortedEmails: [],
};
sendBrochure() {
if (
this.state.tmpSendBrochureEmail !== '' &&
this.state.tmpSendBrochureSubject !== '' &&
this.state.tmpSendBrochureMessage !== '' &&
this.state.sendDocumentList.length > 0 &&
Helpers.isEmailValid(this.state.tmpSendBrochureEmail)
) {
const email = {
email: this.state.tmpSendBrochureEmail,
subject: this.state.tmpSendBrochureSubject,
message: this.state.tmpSendBrochureMessage,
documents: JSON.stringify(this.state.sendDocumentList),
user_id: this.props.currentUser.id
};
this.props.dispatch({ type: 'SEND_BROCHURE', data: email });
this.setState({
showSendBrochure: false,
tmpSendBrochureEmail: '',
tmpSendBrochureSubject: '',
tmpSendBrochureMessage: '',
selectedSendBrochureEmail: -1,
selectedDocument: -1,
sendDocumentList: [],
});
showMessage({
message: i18n.t('global.message_sent') + '.',
description: i18n.t('global.message_will_be_sent_after_sync') + '.',
type: 'success',
duration: 1500,
});
} else {
Alert.alert(
i18n.t('error.incomplete_form'),
i18n.t('error.fill_all_fields_and_1_doc_min') + '.',
);
}
}
transferContact() {
const nextUser = this.props.users.filter(user => user.id !== this.props.currentUser.id)[this.state.selectedTransferUser];
const transferContact = this.state.contactToTransfer;
const contact = {
id: transferContact.id,
email: transferContact.email,
type: transferContact.type,
other: transferContact.other,
network: transferContact.network,
name: transferContact.name,
firstname: transferContact.firstname,
office: transferContact.office,
company: transferContact.company,
address: transferContact.address,
phone: transferContact.phone,
products: transferContact.products,
notes: transferContact.note,
visits: transferContact.visits,
to_delete: false,
synced: false,
user_id: nextUser.id,
};
this.props.dispatch({ type: 'EDIT_CONTACT', data: contact });
this.setState({ showTransferContact: false });
showMessage({
message: i18n.t('contact_s.contact_transferred') + '.',
description: i18n.t('contact_s.contact_will_be_sent_after_sync') + '.',
type: 'success',
duration: 1500,
});
}
deleteContact(id) {
Alert.alert(
i18n.t('global.confirmation'),
i18n.t('contact_s.confirm_contact_delete'),
[
{
text: i18n.t('global.no'),
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: i18n.t('global.yes'),
onPress: () => {
this.setState({ contacts: [], sortedEmails: [] });
this.props.dispatch({ type: 'DELETE_CONTACT', data: id });
showMessage({
message: i18n.t('contact_s.contact_deleted') + '.',
type: 'success',
duration: 500,
});
},
},
],
{ cancelable: false },
);
}
Item(item) {
return (
<View style={styles.item}>
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('ContactDetailsScreen', {
action: 'edit',
contactId: item.id,
})
}>
<Text style={styles.clickable}>
{item.name.toUpperCase()} {item.firstname}
</Text>
</TouchableOpacity>
<Text style={styles.company}>{item.company}</Text>
<Text style={styles.email}>{item.email}</Text>
<View style={styles.buttons}>
<TouchableOpacity
style={styles.button}
onPress={() => {
this.deleteContact(item.id);
}}>
<Icon name="trash" size={20} color={'#ea4f52'} />
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => {
this.setState({
showTransferContact: true,
contactToTransfer: item,
});
}}>
<Icon name="paper-plane" size={20} color={'#ea4f52'} />
</TouchableOpacity>
</View>
</View>
);
}
sortContacts(field) {
let sort;
if (field !== this.state.sortField) {
sort = 'asc';
} else {
if (this.state.sortType === 'asc') {
sort = 'desc';
} else {
sort = 'asc';
}
}
let obj = this.props.contacts;
let array = Object.keys(obj).map(function (key) { return obj[key]; });
this.setState({ contacts: array.sort(Helpers.compareValues(field, sort)), sortType: sort, sortField: field });
//this.setState({ contacts: this.state.contacts.sort(Helpers.compareValues(field, sort)), sortType: sort, sortField: field });
}
HeaderItem() {
return (
<View style={styles.item}>
<TouchableOpacity onPress={() => {
this.sortContacts('name');
}}>
<Text style={styles.clickable}>{i18n.t('global.name')} <Icon name={'sort'} /></Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
this.sortContacts('company');
}}>
<Text style={styles.clickable}>{i18n.t('global.company')} <Icon name={'sort'} /></Text>
</TouchableOpacity>
<Text style={styles.email}>{i18n.t('global.email')}</Text>
<Text style={styles.buttons} />
</View>
);
}
handleSearchBtn() {
if (this.state.searchTxt.length > 0) {
let obj = this.props.contacts;
let array = Object.keys(obj).map(function (key) { return obj[key]; });
this.setState({ contacts: array.sort(Helpers.compareValues('name', 'asc')), sortType: 'asc', searchTxt: '' });
}
}
handleSearchTxt(text) {
this.setState({ searchTxt: text });
if (text.length > 0) {
let tmpContactsName = this.props.contacts.filter(item => item.name.toLowerCase().indexOf(text.toLowerCase()) >= 0);
let tmpContactsCompany = this.props.contacts.filter(item => {
if (item.company === null) {
return false;
}
return item.company.toLowerCase().indexOf(text.toLowerCase()) >= 0
});
let resSearch = Object.assign(tmpContactsName, tmpContactsCompany);
this.setState({ contacts: resSearch.sort(Helpers.compareValues('name', 'asc')), sortType: 'asc' });
} else {
let obj = this.props.contacts;
let array = Object.keys(obj).map(function (key) { return obj[key]; });
this.setState({ contacts: array.sort(Helpers.compareValues('name', 'asc')), sortType: 'asc' });
}
}
componentDidMount() {
this.init();
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.contacts !== this.props.contacts) {
this.init();
}
}
init() {
let objContacts = this.props.contacts;
let objDocs = this.props.documents;
let arrayContacts = Object.keys(objContacts).map(function (key) { return objContacts[key]; });
let arrayEmails = Object.keys(objContacts).map(function (key) { return objContacts[key]; });
let arrayDocs = Object.keys(objDocs).map(function (key) { return objDocs[key]; });
this.setState({
contacts: arrayContacts.sort(Helpers.compareValues('name', 'asc')),
sortedDocuments: arrayDocs.sort(Helpers.compareValues('title', 'asc')),
sortedEmails: arrayEmails.sort(Helpers.compareValues('email', 'asc')),
sortType: 'asc',
sortField: 'name',
});
}
render() {
const { contactAdded } = this.props.route.params;
if (contactAdded === true) {
this.props.navigation.setParams({ contactAdded: false });
showMessage({
message: i18n.t('contact_s.contact_added') + '.',
type: 'success',
duration: 500,
});
}
return (
<View style={styles.container}>
<View
style={{
marginTop: 20,
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
}}>
<Button
color={'#ea4f52'}
title={i18n.t('global.add')}
onPress={() =>
this.props.navigation.navigate('ContactDetailsScreen', {
action: 'add',
})
}
/>
<Button
color={'#ea4f52'}
title={i18n.t('contact_s.send_flyer')}
onPress={() => this.setState({ showSendBrochure: true })}
/>
<View style={{ flexDirection: 'row' }}>
<TextInput placeholder={i18n.t('global.search')} style={styles.inputSearch} value={this.state.searchTxt} onChangeText={(text) => this.handleSearchTxt(text)} />
<TouchableOpacity style={styles.btnSearch} onPress={() => this.handleSearchBtn()}>
{this.state.searchTxt.length > 0 ? (
<Icon name={'times'} size={20} color={'white'} />
) : (
<Icon name={'search'} size={20} color={'white'} />
)}
</TouchableOpacity>
</View>
</View>
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
data={this.state.contacts}
renderItem={({ item }) => this.Item(item)}
ListHeaderComponent={this.HeaderItem.bind(this)}
keyExtractor={item => item.id.toString()}
/>
</View>
<Overlay
isVisible={this.state.showTransferContact}
windowBackgroundColor="rgba(255, 255, 255, .9)"
overlayBackgroundColor="white"
width={400}
height={300}>
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ marginBottom: 10 }}>{i18n.t('contact_s.select_contact')} :</Text>
<Picker
style={{
width: 300,
marginBottom: 15,
paddingLeft: 10,
}}
selectedValue={this.state.selectedTransferUser}
onValueChange={(itemValue, itemIndex) => {
this.setState({ selectedTransferUser: itemIndex });
}}>
{this.props.users.filter(user => user.id !== this.props.currentUser.id).map((item, index) => {
return <Picker.Item label={item.email} value={index} key={item.id.toString()} />;
})}
</Picker>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
width: 400,
}}>
<Button
color={'#ea4f52'}
title={i18n.t('global.cancel')}
onPress={() => this.setState({ showTransferContact: false })}
/>
<Button
color={'#ea4f52'}
title={i18n.t('contact_s.transfer')}
onPress={() => this.transferContact()}
/>
</View>
</View>
</Overlay>
<Overlay
isVisible={this.state.showSendBrochure}
windowBackgroundColor="rgba(255, 255, 255, .9)"
overlayBackgroundColor="white"
width={600}
height={500}>
<View style={{ flex: 1 }}>
<View style={{ flex: 2, flexDirection: 'row' }}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
}}>
<TextInput
style={styles.txtSendBrochure}
placeholder={i18n.t('global.email')}
autoCompleteType="email"
autoCapitalize="none"
keyboardType={'email-address'}
value={this.state.tmpSendBrochureEmail}
onChangeText={text =>
this.setState({ tmpSendBrochureEmail: text })
}
/>
<Picker
style={{
width: 300,
marginBottom: 15,
paddingLeft: 10,
}}
selectedValue={this.state.selectedSendBrochureEmail}
onValueChange={(itemValue, itemIndex) => {
if (itemValue !== '-1') {
this.setState({
tmpSendBrochureEmail: this.state.sortedEmails[itemIndex - 1]
.email,
});
}
}}>
<Picker.Item label={i18n.t('contact_s.contact_list') + ' :'} value="-1" />
{this.state.sortedEmails.map((item, index) => {
return <Picker.Item label={item.email} value={index} key={item.id.toString()} />;
})}
</Picker>
<TextInput
style={styles.txtSendBrochure}
placeholder={i18n.t('global.subject')}
value={this.state.tmpSendBrochureSubject}
onChangeText={text =>
this.setState({ tmpSendBrochureSubject: text })
}
/>
<TextInput
style={styles.textAreaSendBrochure}
placeholder={i18n.t('global.message')}
value={this.state.tmpSendBrochureMessage}
multiline={true}
underlineColorAndroid="transparent"
onChangeText={text =>
this.setState({ tmpSendBrochureMessage: text })
}
/>
<Picker
style={{
width: 300,
marginBottom: 15,
paddingLeft: 10,
}}
selectedValue={this.state.selectedDocument}
onValueChange={(itemValue, itemIndex) => {
if (
itemValue !== '-1' &&
this.state.sendDocumentList.length < 8
) {
let tmp = this.state.sendDocumentList;
const toPush = this.state.sortedDocuments[itemIndex - 1];
const test = this.state.sendDocumentList.filter(
item => item.id === toPush.id,
);
if (test.length === 0) {
tmp.push(toPush);
this.setState({
sendDocumentList: tmp,
});
}
}
}}>
<Picker.Item label={i18n.t('contact_s.documents_list') + ' :'} value="-1" />
{this.state.sortedDocuments.map((item, index) => {
return (
<Picker.Item
label={
item.title + ' (' + item.type.toUpperCase() + ')'
}
value={index}
key={item.id.toString()}
/>
);
})}
</Picker>
</View>
<View
style={{
flex: 1,
borderWidth: 1,
borderColor: 'lightgrey',
alignItems: 'center',
justifyContent: 'center',
width: 600,
}}>
{this.state.sendDocumentList.map((item, index) => {
return (
<TouchableOpacity
onPress={() => {
let tmp = this.state.sendDocumentList;
tmp.splice(this.props.documents[index], 1);
this.setState({
sendDocumentList: tmp,
});
}}>
<View
style={{
borderWidth: 1,
borderColor: 'lightgrey',
padding: 5,
margin: 5,
borderRadius: 5,
}}>
<Text>
{item.title} ({item.type.toUpperCase()}){' '}
<Icon name="minus" size={15} />
</Text>
</View>
</TouchableOpacity>
);
})}
</View>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
width: 600,
marginTop: 15,
}}>
<Button
color={'#ea4f52'}
title={i18n.t('global.cancel')}
onPress={() =>
this.setState({
showSendBrochure: false,
tmpSendBrochureEmail: '',
tmpSendBrochureSubject: '',
tmpSendBrochureMessage: '',
selectedSendBrochureEmail: -1,
selectedDocument: -1,
sendDocumentList: [],
})
}
/>
<Button title={i18n.t('global.send')} onPress={() => this.sendBrochure()} color={'#ea4f52'} />
</View>
</View>
</Overlay>
</View>
);
}
}
const { width } = Dimensions.get('window');
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
},
item: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderBottomWidth: 1,
padding: 15,
marginHorizontal: 15,
},
clickable: {
textAlign: 'center',
fontSize: 18,
width: width / 4,
color: '#ea4f52',
fontWeight: 'bold'
},
company: {
textAlign: 'center',
fontSize: 15,
width: width / 4,
},
email: {
textAlign: 'center',
fontSize: 15,
width: width / 4,
},
buttons: {
justifyContent: 'center',
flexDirection: 'row',
fontSize: 15,
width: width / 4,
},
button: {
width: 35,
height: 35,
justifyContent: 'center',
alignItems: 'center',
margin: 2,
},
txtSendBrochure: {
borderWidth: 1,
borderColor: 'lightgrey',
width: 280,
marginBottom: 5,
paddingLeft: 10,
},
textAreaSendBrochure: {
borderWidth: 1,
borderColor: 'lightgrey',
width: 280,
height: 150,
marginBottom: 5,
paddingLeft: 10,
textAlignVertical: 'top',
},
inputSearch: {
backgroundColor: 'white',
width: 200,
paddingLeft: 20
},
btnSearch: {
width: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ea4f52'
}
});
export default connect(mapStateToProps)(ContactScreen);

View file

@ -1,114 +0,0 @@
import React from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
Text,
} from 'react-native';
import {connect} from 'react-redux';
import TreeView from 'react-native-animated-tree-view';
import Icon from 'react-native-vector-icons/FontAwesome5';
function mapStateToProps(state) {
return {
documents: state.documents,
};
}
class DirectoriesScreen extends React.Component {
state = {
documents: [],
};
showDocuments(folder) {
const documents = this.props.documents.filter(
tmp => tmp.directory === folder.id,
);
this.setState({documents: documents});
}
openDocument(document) {
this.props.dispatch({type: 'SET_CURRENT_OPENED_DOC', data: document});
if (document.type === 'pdf') {
this.props.navigation.navigate('PDFScreen', {uuid: document.uuid});
} else if (document.type === 'mp4') {
this.props.navigation.navigate('VideoScreen', {uuid: document.uuid});
} else {
console.log('Inconnu');
}
}
render() {
const {folder} = this.props.route.params;
let documentList = this.state.documents.map(document => {
return (
<TouchableOpacity
key={document.id.toString()}
style={styles.file}
onPress={() => this.openDocument(document)}>
{document.type === 'pdf' ? (
<Icon name="file-pdf" color={'white'} size={60}/>
) : (
<Icon name="file-video" color={'white'} size={60}/>
)}
<Text style={styles.fileTxt}>{document.title}</Text>
</TouchableOpacity>
);
});
return (
<View style={styles.container}>
<View
style={{width: 290, borderRightWidth: 1, borderColor: 'lightgrey'}}>
<TreeView
data={folder}
leftImage={{}}
rightImage={require('../assets/img/arrow_down.png')}
containerStyle={styles.treeviewContainer}
onClick={tmp => this.showDocuments(tmp)}
/>
</View>
<ScrollView style={styles.scrollview}>
<View style={styles.filesContainer}>{documentList}</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
treeviewContainer: {
width: 290,
},
scrollview: {
flex: 2,
},
filesContainer: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
file: {
justifyContent: 'center',
alignItems: 'center',
height: 200,
width: 180,
backgroundColor: '#ea4f52',
margin: 10,
},
fileTxt: {
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
fontSize: 18,
padding: 5
}
});
export default connect(mapStateToProps)(DirectoriesScreen);

View file

@ -1,112 +0,0 @@
import React from 'react';
import { View, StyleSheet, ImageBackground, TouchableOpacity, Text, Image } from 'react-native';
import { connect } from 'react-redux';
import NetInfo from '@react-native-community/netinfo';
import Sync from '../Controllers/Sync';
import * as SplashScreen from 'expo-splash-screen';
import i18n from "../I18n";
function mapStateToProps(state) {
return {
directories: state.directories,
locale: state.locale,
};
}
class HomeScreen extends React.Component {
state = {
lastSyncCall: '2020-02-12',
};
componentDidMount() {
this.props.dispatch({ type: 'INIT' });
SplashScreen.hideAsync();
}
unsubscribe() {
NetInfo.addEventListener(state => {
if (state.isConnected === true) {
let seconds =
Math.abs(new Date(this.state.lastSyncCall) - Date.now()) / 1000;
//console.log(seconds);
if (seconds > 30) {
this.setState({ lastSyncCall: Date.now() });
Sync.needSync(this.openSync.bind(this));
}
}
});
}
openSync() {
this.props.navigation.navigate('SyncScreen', { isInstalled: true });
}
openFolder(folderID) {
const folder = this.props.directories.filter(tmp => tmp.id === folderID);
this.props.navigation.navigate('DirectoriesScreen', { folder: folder });
}
render() {
i18n.locale = this.props.locale;
this.unsubscribe();
return (
<ImageBackground source={require('../assets/img/background.jpg')} style={{ width: '100%', height: '100%' }}>
<View style={styles.container}>
<TouchableOpacity onPress={() => this.openFolder(2)} style={styles.button}>
<Image source={require('../assets/img/guillemets.png')} style={styles.btnImg} />
<Text style={styles.btnTxt}>{i18n.t('home_s.1')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.openFolder(3)} style={styles.button}>
<Image source={require('../assets/img/guillemets.png')} style={styles.btnImg} />
<Text style={styles.btnTxt}>{i18n.t('home_s.2')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('OnlyVideosScreen')} style={styles.button}>
<Image source={require('../assets/img/guillemets.png')} style={styles.btnImg} />
<Text style={styles.btnTxt}>{i18n.t('global.videos')}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ContactScreen')} style={styles.button}>
<Image source={require('../assets/img/guillemets.png')} style={styles.btnImg} />
<Text style={styles.btnTxt}>{i18n.t('global.contacts')}</Text>
</TouchableOpacity>
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'flex-end',
justifyContent: 'center',
},
text: {
height: 40,
width: 300,
borderColor: 'grey',
borderWidth: 1,
marginBottom: 20,
},
button: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
marginBottom: 20,
marginRight: 50,
width: 400,
height: 80,
borderRadius: 10
},
btnTxt: {
fontSize: 20
},
btnImg: {
position: 'absolute',
left: 15,
height: 50,
width: 50,
resizeMode: 'stretch'
}
});
export default connect(mapStateToProps)(HomeScreen);

View file

@ -1,163 +0,0 @@
import React from 'react';
import { View, StyleSheet, TextInput, Button, Alert, ImageBackground, Image } from 'react-native';
import { connect } from 'react-redux';
import { verify } from 'react-native-b-crypt-bridge';
import Sync from '../Controllers/Sync';
import CommonModel from '../Models/Common';
import * as SplashScreen from 'expo-splash-screen';
import NetInfo from "@react-native-community/netinfo";
import i18n from "../I18n";
function mapStateToProps(state) {
return {
users: state.users,
locale: state.locale,
};
}
class LoginScreen extends React.Component {
state = {
login: '',
password: '',
};
componentDidMount(): void {
SplashScreen.hideAsync();
}
login(login, password) {
if (login !== '' && password !== '') {
let user = this.props.users.filter(tmp => tmp.email === login);
if (user.length > 0) {
user = user[0];
verify(
password,
user.password
).then(verified => {
if (verified === true) {
// Si user === last user
const lastUser = CommonModel.get('lastUser');
if (lastUser !== false && lastUser !== undefined && lastUser.value === user.id.toString()) {
this.loginAction(user);
} else {
// Si la tablette est synchronisée avec le serveur
if (Sync.isSynced()) {
// Si la tablette est connectée à internet pour forcer la synchro
NetInfo.fetch().then(state => {
if (state.isConnected) {
this.loginAction(user, true);
} else {
Alert.alert(i18n.t('error.tablet_not_connected_internet'));
}
});
} else {
Alert.alert(i18n.t('error.tablet_not_synced_last_user'));
}
}
} else {
Alert.alert(i18n.t('error.incorrect_credentials'));
}
}).catch(error => console.log(error));
} else {
Alert.alert(i18n.t('error.incorrect_credentials'));
}
} else {
Alert.alert(i18n.t('error.must_fill_login_fields'));
}
}
loginAction(user, forceSync = false) {
this.setState({ login: '', password: '' });
CommonModel.update({
key: 'isLogged',
value: JSON.stringify(user),
});
CommonModel.update({
key: 'loggedTime',
value: Date.now().toString(),
});
CommonModel.update({ key: 'lastUser', value: user.id.toString() });
this.props.dispatch({
type: 'SET_CURRENT_USER',
data: JSON.stringify(user),
});
this.props.dispatch({ type: 'SET_LOGGED', data: true });
if (forceSync === true) {
this.props.navigation.navigate('SyncScreen', { isInstalled: true, forceSync: true });
}
}
renderInstallBtn() {
if (!Sync.isInstalled()) {
return (
<View style={{ marginTop: 20 }}>
<Button
color={'#ea4f52'}
title={i18n.t('login_s.install')}
onPress={() =>
this.props.navigation.navigate('SyncScreen', { isInstalled: false })
}
/>
</View>
);
}
}
render() {
i18n.locale = this.props.locale;
return (
<ImageBackground source={require('../assets/img/background.jpg')} style={{ width: '100%', height: '100%' }}>
<View style={styles.container}>
<Image source={require('../assets/img/logo-square.png')} style={{ width: 150, height: 150, marginBottom: 20 }} />
{Sync.isInstalled() && (
<View>
<TextInput
style={styles.text}
placeholder={i18n.t('login_s.username')}
value={this.state.login}
onChangeText={text => this.setState({ login: text })}
autoCapitalize={'none'}
autoCorrect={false}
keyboardType={'email-address'}
/>
<TextInput
style={styles.text}
placeholder={i18n.t('login_s.password')}
value={this.state.password}
onChangeText={text => this.setState({ password: text })}
secureTextEntry={true}
autoCapitalize={'none'}
autoCorrect={false}
/>
<Button
title={i18n.t('global.login')}
onPress={() => this.login(this.state.login, this.state.password)}
color={'#ea4f52'}
/>
</View>
)}
{this.renderInstallBtn()}
</View>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
height: 40,
width: 300,
borderColor: 'grey',
borderWidth: 1,
marginBottom: 20,
backgroundColor: 'white',
paddingLeft: 10
},
});
export default connect(mapStateToProps)(LoginScreen);

View file

@ -1,35 +0,0 @@
import React from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
Text,
} from 'react-native';
import {connect} from 'react-redux';
function mapStateToProps(state) {
return {
documents: state.documents,
};
}
class MySpaceScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Mon Espace</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
});
export default connect(mapStateToProps)(MySpaceScreen);

View file

@ -1,95 +0,0 @@
import React from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
Text,
} from 'react-native';
import {connect} from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome5';
function mapStateToProps(state) {
return {
documents: state.documents,
};
}
class OnlyVideosScreen extends React.Component {
state = {
documents: [],
};
showDocuments() {
const documents = this.props.documents.filter(tmp => tmp.type === 'mp4');
this.setState({documents: documents});
}
openDocument(document) {
this.props.dispatch({type: 'SET_CURRENT_OPENED_DOC', data: document});
this.props.navigation.navigate('VideoScreen', {uuid: document.uuid});
}
componentDidMount(): void {
this.showDocuments();
}
render() {
let documentList = this.state.documents.map(document => {
return (
<TouchableOpacity
key={document.id.toString()}
style={styles.file}
onPress={() => this.openDocument(document)}>
{document.type === 'pdf' ? (
<Icon name="file-pdf" color={'white'} size={60}/>
) : (
<Icon name="file-video" color={'white'} size={60}/>
)}
<Text style={styles.fileTxt}>{document.title}</Text>
</TouchableOpacity>
);
});
return (
<View style={styles.container}>
<ScrollView style={styles.scrollview}>
<View style={styles.filesContainer}>{documentList}</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
scrollview: {
flex: 2,
},
filesContainer: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
file: {
justifyContent: 'center',
alignItems: 'center',
height: 200,
width: 180,
backgroundColor: '#ea4f52',
margin: 10,
},
fileTxt: {
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
fontSize: 18,
padding: 5
}
});
export default connect(mapStateToProps)(OnlyVideosScreen);

View file

@ -1,57 +0,0 @@
import React from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import Pdf from 'react-native-pdf';
import * as FileSystem from 'expo-file-system';
class PDFScreen extends React.Component {
render() {
const { uuid } = this.props.route.params;
const source = {
uri: FileSystem.documentDirectory + uuid + '.pdf',
cache: false,
};
return (
<View style={styles.container}>
<Pdf
source={source}
onLoadComplete={(numberOfPages, filePath) => {
console.log(`number of pages: ${numberOfPages}`);
}}
onPageChanged={(page, numberOfPages) => {
console.log(`current page: ${page}`);
}}
onError={error => {
console.log(error);
}}
onPressLink={uri => {
console.log(`Link presse: ${uri}`);
}}
style={styles.pdf}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
height: 40,
width: 300,
borderColor: 'grey',
borderWidth: 1,
marginBottom: 20,
},
pdf: {
flex: 1,
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
});
export default PDFScreen;

View file

@ -1,111 +0,0 @@
import React from 'react';
import {
View,
StyleSheet,
ScrollView,
TouchableOpacity,
Text,
} from 'react-native';
import {connect} from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Helpers from "../Controllers/Helpers";
import i18n from "../I18n";
function mapStateToProps(state) {
return {
documents: state.documents,
};
}
class SearchScreen extends React.Component {
state = {
documents: [],
};
openDocument(document) {
this.props.dispatch({type: 'SET_CURRENT_OPENED_DOC', data: document});
if (document.type === 'pdf') {
this.props.navigation.navigate('PDFScreen', {uuid: document.uuid});
} else if (document.type === 'mp4') {
this.props.navigation.navigate('VideoScreen', {uuid: document.uuid});
} else {
console.log('Inconnu');
}
}
componentDidMount(): void {
const {needle, onlyVideos} = this.props.route.params;
let objDocs = this.props.documents;
let arrayDocs = Object.keys(objDocs).map(function (key) { return objDocs[key]; });
let sorted = arrayDocs.sort(Helpers.compareValues('title', 'asc'));
let filtered = sorted.filter(item => item.title.toLowerCase().indexOf(needle.toLowerCase()) >= 0);
if (onlyVideos === true) {
filtered = filtered.filter(item => item.type === 'mp4');
}
this.setState({
documents: filtered,
});
}
render() {
let documentList = this.state.documents.map(document => {
return (
<TouchableOpacity
key={document.id.toString()}
style={styles.file}
onPress={() => this.openDocument(document)}>
{document.type === 'pdf' ? (
<Icon name="file-pdf" color={'white'} size={60}/>
) : (
<Icon name="file-video" color={'white'} size={60}/>
)}
<Text style={styles.fileTxt}>{document.title}</Text>
</TouchableOpacity>
);
});
return (
<View style={styles.container}>
<ScrollView style={styles.scrollview}>
<View style={styles.filesContainer}>{documentList}</View>
{this.state.documents.length === 0 && (
<Text style={{textAlign: 'center', marginTop: 50, fontSize: 30}}>{i18n.t('search_s.no_result')}</Text>
)}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
scrollview: {
flex: 2,
},
filesContainer: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'center',
},
file: {
justifyContent: 'center',
alignItems: 'center',
height: 200,
width: 180,
backgroundColor: '#ea4f52',
margin: 10,
},
fileTxt: {
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
fontSize: 18,
padding: 5
}
});
export default connect(mapStateToProps)(SearchScreen);

View file

@ -1,320 +0,0 @@
import React from 'react';
import {View, StyleSheet, Button, Alert, Text, Linking} from 'react-native';
import {connect} from 'react-redux';
import * as FileSystem from 'expo-file-system';
import Sync from '../Controllers/Sync';
import * as Progress from 'react-native-progress';
import NetInfo from '@react-native-community/netinfo';
import i18n from "../I18n";
function mapStateToProps(state) {
return {
documents: state.documents,
syncVersion: state.syncVersion,
currentUser: state.currentUser,
};
}
class SyncScreen extends React.Component {
state = {
progress: 0,
txtStep: '',
downloadProgress: 0,
downloadingFile: false,
processing: false,
newApp: false
};
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});
}
const endpoint = Sync.getEndpointDocs();
const doc = documents[i];
this.setState({
txtStep:
i18n.t('sync_s.download') + ' : ' +
doc.title +
' (' +
doc.type.toUpperCase() +
') ...',
});
try {
//console.log(endpoint + doc.uuid + "." + doc.type);
const {uri} = await this.downloadResumable(
endpoint + doc.uuid + "." + doc.type,
doc.uuid,
doc.type,
).downloadAsync();
const {modificationTime} = await FileSystem.getInfoAsync(FileSystem.documentDirectory + doc.uuid + '.' + doc.type);
Sync.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;
}
}
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;
}
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;
}
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);
});
}
});
}
finishSync(version) {
this.props.dispatch({type: 'INIT'});
Sync.updateVersion(version);
this.setState({txtStep: i18n.t('sync_s.update_completed') + '.', processing: false});
if (this.state.newApp === true) {
const appUUID = Sync.getAppUUID();
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},
);
}
}
getDocuments() {
this.setState({progress: 0.4, txtStep: i18n.t('sync_s.updating_docs') + '...'});
Sync.getDocuments(this.downloadDocuments.bind(this));
}
getDirectories() {
this.setState({progress: 0.3, txtStep: i18n.t('sync_s.updating_folders') + '...'});
Sync.getDirectories(this.getDocuments.bind(this));
}
sendBrochures() {
this.setState({progress: 0.2, txtStep: i18n.t('sync_s.sending_flyers') + '...'});
Sync.sendBrochures(this.getDirectories.bind(this));
}
getContacts() {
this.setState({progress: 0.1, txtStep: i18n.t('sync_s.updating_contacts') + '...'});
Sync.getContacts(this.sendBrochures.bind(this), this.props.currentUser.id, this.errorCallback.bind(this));
}
installProcessed() {
Sync.setInstalled();
this.props.dispatch({type: 'INIT_USERS'});
this.setState({
processing: false,
progress: 1,
txtStep: i18n.t('sync_s.user_install_completed') + '.',
});
}
process(version, ShowIsActive, newApp) {
this.props.dispatch({
type: 'UPDATE_VERSION',
data: version,
});
this.props.dispatch({
type: 'UPDATE_SHOW_IS_ACTIVE',
data: ShowIsActive,
});
this.setState({newApp: newApp});
const {isInstalled} = this.props.route.params;
if (isInstalled === false) {
this.setState({txtStep: i18n.t('sync_s.user_install') + '...'});
Sync.getUsers(this.installProcessed.bind(this));
} else {
this.setState({txtStep: i18n.t('sync_s.updating_users') + '...'});
Sync.getUsers(this.getContacts.bind(this));
}
}
fileProgress() {
if (this.state.downloadingFile === true) {
return this.state.downloadProgress + ' %';
}
}
errorCallback(error) {
let msg = '';
let httpCode = '';
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
msg = i18n.t('error.error_has_occurred') + '. Err: 1';
httpCode = error.response.status;
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
//console.log(error.request);
msg = i18n.t('error.error_has_occurred') + '. Err: 2';
} else {
// Something happened in setting up the request that triggered an Error
//console.log('Error', error.message);
msg = i18n.t('error.error_has_occurred') + '. Err: 3';
}
if (httpCode.length > 0) {
Alert.alert(
i18n.t('error.error'),
msg + ' (Code: ' + httpCode + ')',
[{text: 'OK'}],
{cancelable: false},
);
}else{
Alert.alert(
i18n.t('error.error'),
msg,
[{text: 'OK'}],
{cancelable: false},
);
}
this.setState({processing: false});
}
checkConnection() {
NetInfo.fetch().then(state => {
if (state.isConnected) {
this.setState({processing: true});
Sync.getVersion(this.process.bind(this), this.errorCallback.bind(this));
} else {
Alert.alert(
i18n.t('global.warning'),
i18n.t('error.must_be_connected_internet_sync') + '.',
[{text: 'OK'}],
{cancelable: false},
);
}
});
return false;
}
componentDidMount() {
const {forceSync} = this.props.route.params;
if (forceSync === true) {
this.checkConnection();
}
}
render() {
const fileProgress = this.fileProgress();
return (
<View style={styles.container}>
<Progress.Circle
size={250}
progress={this.state.progress}
showsText={true}
color={'#ea4f52'}
/>
<View style={{marginTop: 20}}>
<Button
disabled={this.state.processing}
color={'#ea4f52'}
title={i18n.t('sync_s.start_sync')}
onPress={() => this.checkConnection()}
/>
</View>
<View style={{marginTop: 20}}>
<Text>
{this.state.txtStep} {fileProgress}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
export default connect(mapStateToProps)(SyncScreen);

View file

@ -1,52 +0,0 @@
import React from 'react';
import { View, Dimensions } from 'react-native';
import * as FileSystem from 'expo-file-system';
import VideoPlayer from 'expo-video-player';
import { ResizeMode } from 'expo-av';
class VideoScreen extends React.Component {
render() {
const { uuid } = this.props.route.params;
let width = Dimensions.get("window").width;
let height = Dimensions.get("window").height;
// if portrait
if (height > width) {
let tmpHeight = height;
height = width - 150;
width = tmpHeight + 100;
} else {
height = height - 100;
}
return (
<View style={{ flex: 1, backgroundColor: 'black' }}>
<VideoPlayer
defaultControlsVisible={true}
fullscreen={{
visible: false
}}
slider={{
minimumTrackTintColor: '#ea4f52',
thumbTintColor: '#ea4f52',
}}
style={{
height: height,
width: width
}}
videoProps={{
shouldPlay: true,
resizeMode: ResizeMode.CONTAIN,
source: {
uri: FileSystem.documentDirectory + uuid + '.mp4',
},
}}
/>
</View>
);
}
}
export default VideoScreen;