Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from "react";
- import {
- StyleSheet,
- View,
- Keyboard,
- AsyncStorage,
- Platform,
- NetInfo,
- DeviceEventEmitter,
- Alert,
- Animated,
- Easing,
- Dimensions
- } from "react-native";
- import BackgroundContainer from "../components/backgroundcontainer";
- import axios from "axios";
- import { apiConstants } from "../common/api";
- import Form from "../components/form";
- import FormTextInput from "../components/formtextinput";
- import ListItem from "../components/listitem";
- import Label from "../components/label";
- import { COLOR_WHITE, COLOR_RED } from "../common/colours";
- import ContactGroup from "../components/contactgroup";
- import OfflineMode from "../components/offlinemode";
- import BusinessCard from "../components/businesscard";
- import RNAdvertiseBle from "react-native-advertise-ble";
- import {
- Menu,
- MenuOptions,
- MenuOption,
- MenuTrigger,
- renderers
- } from "react-native-popup-menu";
- import Contacts from "react-native-contacts";
- import helpers from "../common/helpers";
- import { uuidConstants } from "../common/UUID";
- import { BtErrorCode, BtErrorCodeMessage } from "../common/BtErrorCodes";
- const { SlideInMenu } = renderers;
- const screen = {
- height: Dimensions.get("window").height,
- width: Dimensions.get("window").width
- };
- const cardWidth = screen.width - 40;
- const cardHeight = screen.height - 120;
- class ContactsScreen extends React.Component {
- constructor(props) {
- super();
- this.getContacts = this.getContacts.bind(this);
- this.search = this.search.bind(this);
- this.cancelSearch = this.cancelSearch.bind(this);
- this.toggleMenu = this.toggleMenu.bind(this);
- this.deleteContact = this.deleteContact.bind(this);
- this.state = {
- search: "",
- contacts: [],
- originalContacts: [],
- menuIsOpen: false,
- selectedContact: {},
- advertising: false,
- data: null,
- deviceOnline: true,
- yCardPosition: new Animated.Value(cardHeight * -1)
- };
- }
- componentWillMount() {
- NetInfo.isConnected.addEventListener(
- "connectionChange",
- this._handleConnectivityChange
- );
- this.startAdvertising();
- NetInfo.isConnected.fetch().done(isConnected => {
- this.setState({ deviceOnline: isConnected });
- this.getOfflineData().then(() => this.getContacts());
- });
- }
- componentWillUnmount() {
- RNAdvertiseBle.stop();
- NetInfo.removeEventListener(
- "connectionChange",
- this._handleConnectivityChange
- );
- }
- componentDidMount() {
- DeviceEventEmitter.addListener("OnWriteReceived", this._onWriteReceived);
- }
- _handleConnectivityChange = isConnected => {
- this.setState({ deviceOnline: isConnected });
- if (!isConnected) {
- this.getOfflineData();
- } else {
- this.getContacts();
- }
- };
- async getContacts() {
- let UserId = await AsyncStorage.getItem("UserId");
- let url = apiConstants.baseUrl + "/CompanyContact.svc/GetCompanyUserContact";
- let data = {
- Authentication: apiConstants.authentication,
- pklId: UserId
- };
- axios
- .post(url, data)
- .then(this.success.bind(this))
- .catch(this.error.bind(this));
- }
- async getOfflineData() {
- let data = await AsyncStorage.getItem("offline-contacts");
- data = JSON.parse(data);
- if (data == null) {
- } else {
- this.setState({
- contacts: data.CompanyUserContactModel,
- originalContacts: data.CompanyUserContactModel
- });
- }
- }
- async success(response) {
- let data = response.data;
- AsyncStorage.setItem("offline-contacts", JSON.stringify(data));
- if (data.Status.sStatus === apiConstants.apiResults.success) {
- this.downloadOfflineContacts();
- this.setState({
- contacts: data.CompanyUserContactModel,
- originalContacts: data.CompanyUserContactModel
- });
- }
- }
- error(response) {
- this.getOfflineData();
- }
- search(text) {
- if (text !== "") {
- this.setState({ search: text });
- let contacts = Object.create(this.state.originalContacts);
- //search through the array
- let searchResults = contacts.filter(
- contact =>
- contact["sFirstname"].toLowerCase().includes(text.toLowerCase()) ||
- contact["sFirstname"].toLowerCase().includes(text.toLowerCase()) ||
- contact["sFullnmame"].toLowerCase().includes(text.toLowerCase())
- );
- this.setState({ contacts: searchResults });
- } else {
- this.setState({
- search: text,
- contacts: this.state.originalContacts
- });
- }
- }
- cancelSearch() {
- this.setState({ search: "", contacts: this.state.originalContacts });
- Keyboard.dismiss();
- }
- renderCancel() {
- if (this.state.search.length > 0) {
- return (
- <View style={styles.searchCancelContainer}>
- <Label color={COLOR_WHITE} onPress={() => this.cancelSearch()}>
- Cancel
- </Label>
- </View>
- );
- }
- }
- toggleMenu(contact) {
- if (contact) {
- this.setState({
- menuIsOpen: !this.state.menuIsOpen,
- selectedContact: contact
- });
- } else {
- this.setState({ menuIsOpen: !this.state.menuIsOpen });
- }
- }
- renderContacts() {
- //create groups of five
- let contactGroups = [],
- size = 5;
- let contacts = Object.create(this.state.contacts);
- while (contacts.length > 0) contactGroups.push(contacts.splice(0, size));
- return contactGroups.map((contactGroup, index) => {
- return (
- <ContactGroup
- key={index}
- isGroupEvenIndex={index % 2 == 0}
- contacts={contactGroup}
- navigation={this.props.navigation}
- onLongPress={this.toggleMenu}
- />
- );
- });
- }
- saveContactToAddressBook(response) {
- let data = response.data.BusinessCardModel;
- let newContact = {
- emailAddresses: [
- {
- label: "work",
- email: data.sEmail
- }
- ],
- familyName: data.sLastname,
- givenName: data.sFirstname,
- company: data.sCompanyName,
- displayName: data.sFullname,
- jobTitle: data.sJobTitle,
- note: data.sBriefDescription,
- phoneNumbers: [
- {
- label: "mobile",
- number: data.sPhoneNumber
- },
- {
- label: "work",
- number: data.sCompanyPhone
- }
- ],
- hasThumbnail: true,
- thumbnailPath: data.sProfilePicFrontLink,
- urlAddresses: [
- {
- label: "work",
- url: data.sWebsiteUrl
- },
- {
- label: "other",
- url: data.sCardURLShort
- },
- {
- label: "other",
- url: data.sTwitterUrl
- },
- {
- label: "other",
- url: data.sFacebookUrl
- },
- {
- label: "other",
- url: `https://www.linkedin.com/in/${data.sLinkedInUrl}`
- }
- ]
- };
- Contacts.openContactForm(newContact, err => {
- if (err) {
- //handle error opening contacts
- } else {
- this.toggleMenu();
- }
- });
- }
- deleteContact(contact) {
- let url = apiConstants.baseUrl + "/CompanyContact.svc/RemoveCompanyContact";
- //post to server and pass in username and password
- let data = {
- Authentication: apiConstants.authentication,
- pklid: contact.pklid
- };
- axios
- .post(url, data)
- .then(this.deleteSuccess.bind(this))
- .catch(response => console.log(response));
- }
- deleteSuccess(response) {
- this.getContacts();
- this.toggleMenu();
- }
- renderOfflineMode() {
- if (this.state.deviceOnline === false) {
- return <OfflineMode />;
- }
- }
- async startAdvertising() {
- const Firstname = await AsyncStorage.getItem("Firstname");
- const Lastname = await AsyncStorage.getItem("Lastname");
- const FullName = `${Firstname} ${Lastname}`;
- const OperatingSystem = `${
- Platform.OS === "ios" ? "Apple Device" : "Android Device"
- }`;
- const NameCharacteristicData = `${FullName} - ${OperatingSystem}`;
- RNAdvertiseBle.addService(uuidConstants.serviceUUID, true);
- RNAdvertiseBle.addCharacteristicToService(
- uuidConstants.serviceUUID,
- uuidConstants.nameCharacteristicUUID,
- NameCharacteristicData,
- 1,
- 2
- );
- RNAdvertiseBle.addCharacteristicToService(
- uuidConstants.serviceUUID,
- uuidConstants.receiveFileCharacteristicUUID,
- "",
- Platform.OS === "ios" ? 2 : 16, // different permission ints on ios
- 8
- );
- RNAdvertiseBle.start()
- .then(res => {
- this.setState({ adertising: res });
- if (res.errorCode !== BtErrorCode.SUCCESS) {
- this.displayErrorMessage(res.errorCode);
- } else {
- console.log("Starting Advertising...");
- }
- })
- .catch(error => {
- console.log("Failed to start advertising...", res);
- });
- }
- async displayErrorMessage(errorCode) {
- let notifiedAboutAdvertising = await AsyncStorage.getItem("errorBt");
- if (notifiedAboutAdvertising === null) {
- // TODO - make this json and specify which errors the user was notified about previously
- AsyncStorage.setItem("errorBt", "asdfghjkl");
- } else {
- return;
- }
- switch (errorCode) {
- case BtErrorCode.NO_DEFAULT_ADAPTER:
- alert(BtErrorCodeMessage.NO_DEFAULT_ADAPTER);
- break;
- case BtErrorCode.MULTIPLE_ADVERTISING_NOT_SUPPORTED:
- alert(BtErrorCodeMessage.MULTIPLE_ADVERTISING_NOT_SUPPORTED);
- break;
- case BtErrorCode.ADVERTISING_NOT_SUPPORTED:
- alert(BtErrorCodeMessage.ADVERTISING_NOT_SUPPORTED);
- break;
- case BtErrorCode.ADVERTISING_COULD_NOT_START:
- alert(BtErrorCodeMessage.ADVERTISING_COULD_NOT_START);
- break;
- }
- }
- /**
- * Event called when the device's receive file characteristic changes
- * @param {object} response The data written to the characteristic
- * @param {string} response.data.name The sender's full name
- * @param {string} response.data.userGuid The sender's GUID
- * @param {string} response.data.CompanyGuid The sender's company's GUID
- */
- _onWriteReceived = response => {
- console.log("Received characteristic", response);
- if (Platform.OS !== "ios") {
- const ResponseJson = JSON.parse(response.data);
- const Contact = {
- sUserGuid: ResponseJson.userGuid,
- sCompanyGuid: ResponseJson.CompanyGuid
- };
- const AlertMessage = `${
- ResponseJson.name
- } has sent you their business card, would you like to receive it?`;
- // Slide the card in
- this.animateCardSlideIn(Contact.sUserGuid, Contact.sCompanyGuid);
- helpers.alertYesNo(
- "Business Card Incoming",
- AlertMessage,
- () => {
- // Accept button callback
- this.saveContact(Contact.sUserGuid);
- this.setState({
- yCardPosition: cardHeight * -1,
- data: null
- });
- },
- () => {
- // Cancel button callback
- this.setState({
- yCardPosition: cardHeight * -1,
- data: null
- });
- }
- );
- }
- };
- saveContact(guid) {
- if (this.state.deviceOnline) {
- this.saveContactToServer(guid);
- } else {
- this.saveContactOffline(guid);
- }
- }
- /**
- * Saves the new contact to the user's contact list in the database
- * @param {string} guid The sender's GUID
- */
- async saveContactToServer(guid) {
- let url = apiConstants.baseUrl + "/CompanyContact.svc/SaveCompanyContact";
- let userId = await AsyncStorage.getItem("UserId");
- let data = {
- Authentication: apiConstants.authentication,
- NewContactsUserGuid: guid,
- OwnersUserId: userId
- };
- axios
- .post(url, data)
- .then(this.getContacts())
- .catch(err => console.log(err));
- }
- /**
- * Saves contact in async storage
- * @param {string} guid The sender's GUID
- */
- async saveContactOffline(guid) {
- let data = await AsyncStorage.getItem("offline-contacts-storage");
- // Adding a deliminator if the storage isn't empty
- if (data == null) {
- data = "";
- } else {
- data += "#";
- }
- AsyncStorage.setItem("offline-contacts-storage", data + guid);
- }
- async downloadOfflineContacts() {
- let data = await AsyncStorage.getItem("offline-contacts-storage");
- if (data == null) return;
- const Split = data.split("#");
- if (Split.length === 1) {
- this.saveContactToServer(data);
- } else {
- Split.forEach(item => {
- this.saveContactToServer(item);
- });
- }
- AsyncStorage.removeItem("offline-contacts-storage");
- }
- getBusinessCardForContact(contact) {
- let url = apiConstants.baseUrl + "/BusinessCard.svc/GetBusinessCard";
- //post to server and pass in username and password
- let data = {
- Authentication: apiConstants.authentication,
- sCompanyGuid: contact.sCompanyGuid,
- sUserGuid: contact.sUserGuid
- };
- axios
- .post(url, data)
- .then(this.saveContactToAddressBook.bind(this))
- .catch(this.businessCardError.bind(this));
- }
- businessCardError() {
- console.log("There was an error saving this business card.");
- }
- async animateCardSlideIn(userGuid, companyGuid) {
- this.getCard(userGuid, companyGuid);
- Animated.timing(this.state.yCardPosition, {
- toValue: 20,
- duration: 2000
- }).start();
- }
- async getCard(userGuid, companyGuid) {
- let url = apiConstants.baseUrl + "/BusinessCard.svc/GetBusinessCard";
- // Post to server and pass in username and password
- let data = {
- Authentication: apiConstants.authentication,
- sCompanyGuid: companyGuid,
- sUserGuid: userGuid
- };
- axios
- .post(url, data)
- .then(result => {
- this.setState({ data: result.data.BusinessCardModel });
- console.log("worked");
- })
- .catch(err => {
- console.log(err);
- });
- }
- renderContactCard() {
- if (this.state.data == null) return null;
- return (
- <Animated.View
- style={{
- position: "absolute",
- bottom: 0,
- left: 0,
- right: 0,
- justifyContent: "center",
- alignItems: "center",
- top: this.state.yCardPosition,
- zIndex: 99999
- }}>
- <BusinessCard
- width={cardWidth}
- height={cardHeight}
- data={this.state.data}
- isContact={null}
- navigation={this.props.navigation}
- />
- </Animated.View>
- );
- }
- render() {
- return (
- <BackgroundContainer>
- {this.renderContactCard()}
- <View style={{ paddingTop: helpers.paddingTop }}>
- <Menu
- renderer={SlideInMenu}
- opened={this.state.menuIsOpen}
- onBackdropPress={() => this.toggleMenu()}>
- <MenuTrigger />
- <MenuOptions>
- <MenuOption>
- <ListItem
- header={`${
- this.state.selectedContact.sFirstname
- } ${this.state.selectedContact.sLastname} - ${
- this.state.selectedContact.sCompanyName
- }`}
- />
- </MenuOption>
- <MenuOption>
- <ListItem
- header={"Save to contacts"}
- showChevron
- onPress={() =>
- this.getBusinessCardForContact(
- this.state.selectedContact
- )
- }
- />
- </MenuOption>
- <MenuOption>
- <ListItem
- header={"Delete"}
- onPress={() =>
- this.deleteContact(this.state.selectedContact)
- }
- color={COLOR_RED}
- showChevron
- />
- </MenuOption>
- </MenuOptions>
- </Menu>
- {this.renderOfflineMode()}
- <View style={styles.searchContainer}>
- <View style={styles.searchInputContainer}>
- <FormTextInput
- autoCapitalize={false}
- placeholder="Search Contacts... "
- text={this.state.search}
- onChangeText={text => this.search(text)}
- />
- </View>
- {this.renderCancel()}
- </View>
- <Form style={{ marginTop: 0 }}>
- <View style={styles.contactsContainer}>
- {this.renderContacts()}
- </View>
- </Form>
- </View>
- </BackgroundContainer>
- );
- }
- }
- const styles = StyleSheet.create({
- searchContainer: {
- flexDirection: "row",
- justifyContent: "flex-start",
- marginTop: 15,
- marginLeft: 12,
- marginRight: 12
- },
- searchInputContainer: {
- flex: 1,
- flexDirection: "column"
- },
- searchCancelContainer: {
- marginLeft: 5,
- marginBottom: 10,
- flexDirection: "row",
- alignItems: "center",
- justifyContent: "center"
- },
- contactsContainer: {
- flexDirection: "row",
- flexWrap: "wrap",
- marginBottom: 90
- }
- });
- export default ContactsScreen;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement