<commit_before>import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { Form, Modal, Input } from 'antd';
import { WalletContext } from 'utils/context';
import {
    TokenParamLabel,
    MessageVerificationParamLabel,
    WalletInfoCtn,
    ZeroBalanceHeader,
    SidePaddingCtn,
} from 'components/Common/Atoms';
import WalletLabel from 'components/Common/WalletLabel.js';
import BalanceHeader from 'components/Common/BalanceHeader';
import BalanceHeaderFiat from 'components/Common/BalanceHeaderFiat';
import {
    errorNotification,
    messageSignedNotification,
    generalNotification,
} from 'components/Common/Notifications';
import { CustomCollapseCtn } from 'components/Common/StyledCollapse';
import {
    AntdFormWrapper,
    DestinationAddressSingleWithoutQRScan,
} from 'components/Common/EnhancedInputs';
const { TextArea } = Input;
import {
    toLegacyCash,
    convertToEcashPrefix,
    getWalletState,
} from 'utils/cashMethods';
import CopyToClipboard from 'components/Common/CopyToClipboard';
import { ThemedCopySolid } from 'components/Common/CustomIcons';
import { SmartButton } from 'components/Common/PrimaryButton';
import { PlusSquareOutlined } from '@ant-design/icons';
import { currency, parseAddressForParams } from 'components/Common/Ticker.js';
import { isValidXecAddress, isValidEtokenAddress } from 'utils/validation';

const Wrapper = styled.div`
    .ant-collapse {
        &:first-child {
            margin-top: 30px;
        }
    }
`;

const SignMessageLabel = styled.div`
    text-align: left;
    color: ${props => props.theme.forms.text};
`;
const AddressCopyCtn = styled.div`
    display: flex;
    align-items: center;
    gap: 0.5rem;

    svg {
        height: 30px;
        width: 30px;
        &:hover {
            fill: ${props => props.theme.eCashBlue};
            cursor: pointer;
        }
    }
`;

const VerifyMessageLabel = styled.div`
    text-align: left;
    color: ${props => props.theme.forms.text};
`;

const SignatureValidation = styled.div`
    color: ${props => props.theme.encryptionRed};
`;

const SignVerifyMsg = ({ jestBCH }) => {
    const ContextValue = React.useContext(WalletContext);
    const { BCH, wallet, fiatPrice, cashtabSettings, changeCashtabSettings } =
        ContextValue;
    const walletState = getWalletState(wallet);
    const { balances } = walletState;
    const [messageSignature, setMessageSignature] = useState('');
    const [showConfirmMsgToSign, setShowConfirmMsgToSign] = useState(false);
    const [msgToSign, setMsgToSign] = useState('');
    const [sigCopySuccess, setSigCopySuccess] = useState('');
    const [signMessageIsValid, setSignMessageIsValid] = useState(null);
    const [showConfirmMsgToVerify, setShowConfirmMsgToVerify] = useState(false);
    const [messageVerificationAddr, setMessageVerificationAddr] = useState('');
    const [bchObj, setBchObj] = useState(false);
    const [messageVerificationSig, setMessageVerificationSig] = useState('');
    const [messageVerificationMsg, setMessageVerificationMsg] = useState('');
    const [messageVerificationMsgIsValid, setMessageVerificationMsgIsValid] =
        useState(false);
    const [messageVerificationAddrError, setMessageVerificationAddrError] =
        useState(false);
    const [messageVerificationAddrIsValid, setMessageVerificationAddrIsValid] =
        useState(false);
    const [messageVerificationSigIsValid, setMessageVerificationSigIsValid] =
        useState(false);
    const [messageVerificationSigError, setMessageVerificationSigError] =
        useState(false);
    const signMessageByPk = async () => {
        try {
            const messageSignature =
                await BCH.BitcoinCash.signMessageWithPrivKey(
                    wallet.Path1899.fundingWif,
                    msgToSign,
                );
            setMessageSignature(messageSignature);
            messageSignedNotification(messageSignature);
        } catch (err) {
            let message;
            if (!err.error && !err.message) {
                message = err.message || err.error || JSON.stringify(err);
            }
            errorNotification(err, message, 'Message Signing Error');
            throw err;
        }
        // Hide the modal
        setShowConfirmMsgToSign(false);
        setSigCopySuccess('');
    };

    const handleSignMsgChange = e => {
        const { value } = e.target;
        // validation
        if (value && value.length && value.length < 150) {
            setMsgToSign(value);
            setSignMessageIsValid(true);
        } else {
            setSignMessageIsValid(false);
        }
    };

    const verifyMessageBySig = async () => {
        let verification;
        try {
            verification = await bchObj.BitcoinCash.verifyMessage(
                toLegacyCash(messageVerificationAddr),
                messageVerificationSig,
                messageVerificationMsg,
            );
        } catch (err) {
            errorNotification(
                'Error',
                'Unable to execute signature verification',
            );
        }

        if (verification) {
            generalNotification('Signature successfully verified', 'Verified');
        } else {
            errorNotification(
                'Error',
                'Signature does not match address and message',
            );
        }

        setShowConfirmMsgToVerify(false);
    };

    const handleOnSigCopy = () => {
        if (messageSignature != '') {
            setSigCopySuccess('Signature copied to clipboard');
        }
    };

    const handleVerifyMsgChange = e => {
        const { value } = e.target;

        // validation
        if (value && value.length && value.length < 150) {
            setMessageVerificationMsgIsValid(true);
        } else {
            setMessageVerificationMsgIsValid(false);
        }

        setMessageVerificationMsg(value);
    };

    const handleVerifySigChange = e => {
        const { value } = e.target;

        // validation
        if (value && value.length && value.length === 88) {
            setMessageVerificationSigIsValid(true);
            setMessageVerificationSigError(false);
        } else {
            setMessageVerificationSigIsValid(false);
            setMessageVerificationSigError('Invalid signature');
        }

        setMessageVerificationSig(value);
    };

    const handleMessageVerificationAddrChange = e => {
        const { value } = e.target;
        let error = false;
        let addressString = value;
        // parse address for parameters
        const addressInfo = parseAddressForParams(addressString);
        // validate address
        const isValid = isValidXecAddress(addressInfo.address);

        const { address } = addressInfo;

        // Is this valid address?
        if (!isValid) {
            error = `Invalid ${currency.ticker} address`;
            // If valid address but token format
            if (isValidEtokenAddress(address)) {
                error = `eToken addresses are not supported for signature verifications`;
            }
            setMessageVerificationAddrIsValid(false);
        } else {
            setMessageVerificationAddrIsValid(true);
        }
        setMessageVerificationAddrError(error);
        setMessageVerificationAddr(address);
    };

    useEffect(() => {
        // jestBCH is only ever specified for unit tests, otherwise app will use getBCH();
        const activeBCH = jestBCH ? jestBCH : BCH;

        // set the BCH instance to state, for other functions to reference
        setBchObj(activeBCH);
    }, [BCH]);

    return (
        <Wrapper>
            <WalletInfoCtn>
                <WalletLabel
                    name={wallet.name}
                    cashtabSettings={cashtabSettings}
                    changeCashtabSettings={changeCashtabSettings}
                ></WalletLabel>
                {!balances.totalBalance ? (
                    <ZeroBalanceHeader>
                        You currently have 0 {currency.ticker}

                        Deposit some funds to use this feature
                    </ZeroBalanceHeader>
                ) : (
                    <>
                        <BalanceHeader
                            balance={balances.totalBalance}
                            ticker={currency.ticker}
                            cashtabSettings={cashtabSettings}
                        />

                        <BalanceHeaderFiat
                            balance={balances.totalBalance}
                            settings={cashtabSettings}
                            fiatPrice={fiatPrice}
                        />
                    </>
                )}
            </WalletInfoCtn>{' '}
            <SidePaddingCtn>
                <Modal
                    title={`Please review and confirm your message to be signed using this wallet.`}
                    open={showConfirmMsgToSign}
                    onOk={signMessageByPk}
                    onCancel={() => setShowConfirmMsgToSign(false)}
                >
                    <TokenParamLabel>Message:</TokenParamLabel> {msgToSign}

                </Modal>
                <CustomCollapseCtn panelHeader="Sign Message">
                    <AntdFormWrapper>
                        <Form
                            size="small"
                            style={{
                                width: 'auto',
                            }}
                        >
                            <Form.Item>
                                <SignMessageLabel>Message:</SignMessageLabel>
                                <TextArea
                                    name="signMessage"
                                    onChange={e => handleSignMsgChange(e)}
                                    showCount
                                    maxLength={150}
                                />
                            </Form.Item>
                            <Form.Item>
                                <SignMessageLabel>Address:</SignMessageLabel>
                                {wallet &&
                                    wallet.Path1899 &&
                                    wallet.Path1899.cashAddress && (
                                        <AddressCopyCtn>
                                            <Input
                                                name="signMessageAddress"
                                                disabled={true}
                                                value={
                                                    wallet &&
                                                    wallet.Path1899 &&
                                                    wallet.Path1899.cashAddress
                                                        ? convertToEcashPrefix(
                                                              wallet.Path1899
                                                                  .cashAddress,
                                                          )
                                                        : ''
                                                }
                                            />
                                            <CopyToClipboard
                                                data={convertToEcashPrefix(
                                                    wallet.Path1899.cashAddress,
                                                )}
                                                optionalOnCopyNotification={{
                                                    title: 'Copied',
                                                    msg: `${convertToEcashPrefix(
                                                        wallet.Path1899
                                                            .cashAddress,
                                                    )} copied to clipboard`,
                                                }}
                                            >
                                                <ThemedCopySolid />
                                            </CopyToClipboard>
                                        </AddressCopyCtn>
                                    )}
                            </Form.Item>
                            <SmartButton
                                onClick={() => setShowConfirmMsgToSign(true)}
                                disabled={!signMessageIsValid}
                            >
                                <PlusSquareOutlined />
                                 Sign Message
                            </SmartButton>
                            <CopyToClipboard
                                data={messageSignature}
                                optionalOnCopyNotification={{
                                    title: 'Message signature copied to clipboard',
                                    msg: `${messageSignature}`,
                                }}
                            >
                                <Form.Item>
                                    <SignMessageLabel>
                                        Signature:
                                    </SignMessageLabel>
                                    <TextArea
                                        name="signMessageSignature"
                                        placeholder="The signature will be generated upon signing of the message"
                                        readOnly={true}
                                        value={messageSignature}
                                        onClick={() => handleOnSigCopy()}
                                    />
                                </Form.Item>
                            </CopyToClipboard>
                            {sigCopySuccess}
                        </Form>
                    </AntdFormWrapper>
                </CustomCollapseCtn>
                <Modal
                    title={`Please review and confirm your message, signature and address to be verified.`}
                    open={showConfirmMsgToVerify}
                    onOk={verifyMessageBySig}
                    onCancel={() => setShowConfirmMsgToVerify(false)}
                >
                    <MessageVerificationParamLabel>
                        Message:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationMsg}

                    <MessageVerificationParamLabel>
                        Address:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationAddr}

                    <MessageVerificationParamLabel>
                        Signature:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationSig}

                </Modal>
                <CustomCollapseCtn panelHeader="Verify Message">
                    <AntdFormWrapper>
                        <Form
                            size="small"
                            style={{
                                width: 'auto',
                            }}
                        >
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Message:
                                </VerifyMessageLabel>
                                <TextArea
                                    name="verifyMessage"
                                    onChange={e => handleVerifyMsgChange(e)}
                                    showCount
                                    maxLength={150}
                                />
                            </Form.Item>
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Address:
                                </VerifyMessageLabel>
                                <DestinationAddressSingleWithoutQRScan
                                    validateStatus={
                                        messageVerificationAddrError
                                            ? 'error'
                                            : ''
                                    }
                                    help={
                                        messageVerificationAddrError
                                            ? messageVerificationAddrError
                                            : ''
                                    }
                                    inputProps={{
                                        placeholder: `${currency.ticker} Address`,
                                        name: 'address',
                                        onChange: e =>
                                            handleMessageVerificationAddrChange(
                                                e,
                                            ),
                                        required: true,
                                    }}
                                ></DestinationAddressSingleWithoutQRScan>
                            </Form.Item>
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Signature:
                                </VerifyMessageLabel>
                                <TextArea
                                    name="verifySignature"
                                    onChange={e => handleVerifySigChange(e)}
                                    showCount
                                />
                                <SignatureValidation>
                                    {messageVerificationSigError}
                                </SignatureValidation>
                            </Form.Item>
                            <SmartButton
                                onClick={() => setShowConfirmMsgToVerify(true)}
                                disabled={
                                    !messageVerificationAddrIsValid ||
                                    !messageVerificationSigIsValid ||
                                    !messageVerificationMsgIsValid
                                }
                            >
                                <PlusSquareOutlined />
                                 Verify Message
                            </SmartButton>
                        </Form>
                    </AntdFormWrapper>
                </CustomCollapseCtn>
            </SidePaddingCtn>
        </Wrapper>
    );
};

SignVerifyMsg.propTypes = {
    jestBCH: PropTypes.object,
    cashtabSettings: PropTypes.oneOfType([
        PropTypes.shape({
            fiatCurrency: PropTypes.string,
            sendModal: PropTypes.bool,
            autoCameraOn: PropTypes.bool,
            hideMessagesFromUnknownSender: PropTypes.bool,
            toggleShowHideBalance: PropTypes.bool,
        }),
        PropTypes.bool,
    ]),
    changeCashtabSettings: PropTypes.func,
};

export default SignVerifyMsg;
<commit_msg>[Cashtab] [p1 local msg verify] Verify function is not async<commit_after>import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { Form, Modal, Input } from 'antd';
import { WalletContext } from 'utils/context';
import {
    TokenParamLabel,
    MessageVerificationParamLabel,
    WalletInfoCtn,
    ZeroBalanceHeader,
    SidePaddingCtn,
} from 'components/Common/Atoms';
import WalletLabel from 'components/Common/WalletLabel.js';
import BalanceHeader from 'components/Common/BalanceHeader';
import BalanceHeaderFiat from 'components/Common/BalanceHeaderFiat';
import {
    errorNotification,
    messageSignedNotification,
    generalNotification,
} from 'components/Common/Notifications';
import { CustomCollapseCtn } from 'components/Common/StyledCollapse';
import {
    AntdFormWrapper,
    DestinationAddressSingleWithoutQRScan,
} from 'components/Common/EnhancedInputs';
const { TextArea } = Input;
import {
    toLegacyCash,
    convertToEcashPrefix,
    getWalletState,
} from 'utils/cashMethods';
import CopyToClipboard from 'components/Common/CopyToClipboard';
import { ThemedCopySolid } from 'components/Common/CustomIcons';
import { SmartButton } from 'components/Common/PrimaryButton';
import { PlusSquareOutlined } from '@ant-design/icons';
import { currency, parseAddressForParams } from 'components/Common/Ticker.js';
import { isValidXecAddress, isValidEtokenAddress } from 'utils/validation';

const Wrapper = styled.div`
    .ant-collapse {
        &:first-child {
            margin-top: 30px;
        }
    }
`;

const SignMessageLabel = styled.div`
    text-align: left;
    color: ${props => props.theme.forms.text};
`;
const AddressCopyCtn = styled.div`
    display: flex;
    align-items: center;
    gap: 0.5rem;

    svg {
        height: 30px;
        width: 30px;
        &:hover {
            fill: ${props => props.theme.eCashBlue};
            cursor: pointer;
        }
    }
`;

const VerifyMessageLabel = styled.div`
    text-align: left;
    color: ${props => props.theme.forms.text};
`;

const SignatureValidation = styled.div`
    color: ${props => props.theme.encryptionRed};
`;

const SignVerifyMsg = ({ jestBCH }) => {
    const ContextValue = React.useContext(WalletContext);
    const { BCH, wallet, fiatPrice, cashtabSettings, changeCashtabSettings } =
        ContextValue;
    const walletState = getWalletState(wallet);
    const { balances } = walletState;
    const [messageSignature, setMessageSignature] = useState('');
    const [showConfirmMsgToSign, setShowConfirmMsgToSign] = useState(false);
    const [msgToSign, setMsgToSign] = useState('');
    const [sigCopySuccess, setSigCopySuccess] = useState('');
    const [signMessageIsValid, setSignMessageIsValid] = useState(null);
    const [showConfirmMsgToVerify, setShowConfirmMsgToVerify] = useState(false);
    const [messageVerificationAddr, setMessageVerificationAddr] = useState('');
    const [bchObj, setBchObj] = useState(false);
    const [messageVerificationSig, setMessageVerificationSig] = useState('');
    const [messageVerificationMsg, setMessageVerificationMsg] = useState('');
    const [messageVerificationMsgIsValid, setMessageVerificationMsgIsValid] =
        useState(false);
    const [messageVerificationAddrError, setMessageVerificationAddrError] =
        useState(false);
    const [messageVerificationAddrIsValid, setMessageVerificationAddrIsValid] =
        useState(false);
    const [messageVerificationSigIsValid, setMessageVerificationSigIsValid] =
        useState(false);
    const [messageVerificationSigError, setMessageVerificationSigError] =
        useState(false);
    const signMessageByPk = async () => {
        try {
            const messageSignature =
                await BCH.BitcoinCash.signMessageWithPrivKey(
                    wallet.Path1899.fundingWif,
                    msgToSign,
                );
            setMessageSignature(messageSignature);
            messageSignedNotification(messageSignature);
        } catch (err) {
            let message;
            if (!err.error && !err.message) {
                message = err.message || err.error || JSON.stringify(err);
            }
            errorNotification(err, message, 'Message Signing Error');
            throw err;
        }
        // Hide the modal
        setShowConfirmMsgToSign(false);
        setSigCopySuccess('');
    };

    const handleSignMsgChange = e => {
        const { value } = e.target;
        // validation
        if (value && value.length && value.length < 150) {
            setMsgToSign(value);
            setSignMessageIsValid(true);
        } else {
            setSignMessageIsValid(false);
        }
    };

    const verifyMessageBySig = () => {
        let verification;
        try {
            verification = bchObj.BitcoinCash.verifyMessage(
                toLegacyCash(messageVerificationAddr),
                messageVerificationSig,
                messageVerificationMsg,
            );
        } catch (err) {
            errorNotification(
                'Error',
                'Unable to execute signature verification',
            );
        }

        if (verification) {
            generalNotification('Signature successfully verified', 'Verified');
        } else {
            errorNotification(
                'Error',
                'Signature does not match address and message',
            );
        }

        setShowConfirmMsgToVerify(false);
    };

    const handleOnSigCopy = () => {
        if (messageSignature != '') {
            setSigCopySuccess('Signature copied to clipboard');
        }
    };

    const handleVerifyMsgChange = e => {
        const { value } = e.target;

        // validation
        if (value && value.length && value.length < 150) {
            setMessageVerificationMsgIsValid(true);
        } else {
            setMessageVerificationMsgIsValid(false);
        }

        setMessageVerificationMsg(value);
    };

    const handleVerifySigChange = e => {
        const { value } = e.target;

        // validation
        if (value && value.length && value.length === 88) {
            setMessageVerificationSigIsValid(true);
            setMessageVerificationSigError(false);
        } else {
            setMessageVerificationSigIsValid(false);
            setMessageVerificationSigError('Invalid signature');
        }

        setMessageVerificationSig(value);
    };

    const handleMessageVerificationAddrChange = e => {
        const { value } = e.target;
        let error = false;
        let addressString = value;
        // parse address for parameters
        const addressInfo = parseAddressForParams(addressString);
        // validate address
        const isValid = isValidXecAddress(addressInfo.address);

        const { address } = addressInfo;

        // Is this valid address?
        if (!isValid) {
            error = `Invalid ${currency.ticker} address`;
            // If valid address but token format
            if (isValidEtokenAddress(address)) {
                error = `eToken addresses are not supported for signature verifications`;
            }
            setMessageVerificationAddrIsValid(false);
        } else {
            setMessageVerificationAddrIsValid(true);
        }
        setMessageVerificationAddrError(error);
        setMessageVerificationAddr(address);
    };

    useEffect(() => {
        // jestBCH is only ever specified for unit tests, otherwise app will use getBCH();
        const activeBCH = jestBCH ? jestBCH : BCH;

        // set the BCH instance to state, for other functions to reference
        setBchObj(activeBCH);
    }, [BCH]);

    return (
        <Wrapper>
            <WalletInfoCtn>
                <WalletLabel
                    name={wallet.name}
                    cashtabSettings={cashtabSettings}
                    changeCashtabSettings={changeCashtabSettings}
                ></WalletLabel>
                {!balances.totalBalance ? (
                    <ZeroBalanceHeader>
                        You currently have 0 {currency.ticker}

                        Deposit some funds to use this feature
                    </ZeroBalanceHeader>
                ) : (
                    <>
                        <BalanceHeader
                            balance={balances.totalBalance}
                            ticker={currency.ticker}
                            cashtabSettings={cashtabSettings}
                        />

                        <BalanceHeaderFiat
                            balance={balances.totalBalance}
                            settings={cashtabSettings}
                            fiatPrice={fiatPrice}
                        />
                    </>
                )}
            </WalletInfoCtn>{' '}
            <SidePaddingCtn>
                <Modal
                    title={`Please review and confirm your message to be signed using this wallet.`}
                    open={showConfirmMsgToSign}
                    onOk={signMessageByPk}
                    onCancel={() => setShowConfirmMsgToSign(false)}
                >
                    <TokenParamLabel>Message:</TokenParamLabel> {msgToSign}

                </Modal>
                <CustomCollapseCtn panelHeader="Sign Message">
                    <AntdFormWrapper>
                        <Form
                            size="small"
                            style={{
                                width: 'auto',
                            }}
                        >
                            <Form.Item>
                                <SignMessageLabel>Message:</SignMessageLabel>
                                <TextArea
                                    name="signMessage"
                                    onChange={e => handleSignMsgChange(e)}
                                    showCount
                                    maxLength={150}
                                />
                            </Form.Item>
                            <Form.Item>
                                <SignMessageLabel>Address:</SignMessageLabel>
                                {wallet &&
                                    wallet.Path1899 &&
                                    wallet.Path1899.cashAddress && (
                                        <AddressCopyCtn>
                                            <Input
                                                name="signMessageAddress"
                                                disabled={true}
                                                value={
                                                    wallet &&
                                                    wallet.Path1899 &&
                                                    wallet.Path1899.cashAddress
                                                        ? convertToEcashPrefix(
                                                              wallet.Path1899
                                                                  .cashAddress,
                                                          )
                                                        : ''
                                                }
                                            />
                                            <CopyToClipboard
                                                data={convertToEcashPrefix(
                                                    wallet.Path1899.cashAddress,
                                                )}
                                                optionalOnCopyNotification={{
                                                    title: 'Copied',
                                                    msg: `${convertToEcashPrefix(
                                                        wallet.Path1899
                                                            .cashAddress,
                                                    )} copied to clipboard`,
                                                }}
                                            >
                                                <ThemedCopySolid />
                                            </CopyToClipboard>
                                        </AddressCopyCtn>
                                    )}
                            </Form.Item>
                            <SmartButton
                                onClick={() => setShowConfirmMsgToSign(true)}
                                disabled={!signMessageIsValid}
                            >
                                <PlusSquareOutlined />
                                 Sign Message
                            </SmartButton>
                            <CopyToClipboard
                                data={messageSignature}
                                optionalOnCopyNotification={{
                                    title: 'Message signature copied to clipboard',
                                    msg: `${messageSignature}`,
                                }}
                            >
                                <Form.Item>
                                    <SignMessageLabel>
                                        Signature:
                                    </SignMessageLabel>
                                    <TextArea
                                        name="signMessageSignature"
                                        placeholder="The signature will be generated upon signing of the message"
                                        readOnly={true}
                                        value={messageSignature}
                                        onClick={() => handleOnSigCopy()}
                                    />
                                </Form.Item>
                            </CopyToClipboard>
                            {sigCopySuccess}
                        </Form>
                    </AntdFormWrapper>
                </CustomCollapseCtn>
                <Modal
                    title={`Please review and confirm your message, signature and address to be verified.`}
                    open={showConfirmMsgToVerify}
                    onOk={verifyMessageBySig}
                    onCancel={() => setShowConfirmMsgToVerify(false)}
                >
                    <MessageVerificationParamLabel>
                        Message:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationMsg}

                    <MessageVerificationParamLabel>
                        Address:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationAddr}

                    <MessageVerificationParamLabel>
                        Signature:
                    </MessageVerificationParamLabel>{' '}
                    {messageVerificationSig}

                </Modal>
                <CustomCollapseCtn panelHeader="Verify Message">
                    <AntdFormWrapper>
                        <Form
                            size="small"
                            style={{
                                width: 'auto',
                            }}
                        >
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Message:
                                </VerifyMessageLabel>
                                <TextArea
                                    name="verifyMessage"
                                    onChange={e => handleVerifyMsgChange(e)}
                                    showCount
                                    maxLength={150}
                                />
                            </Form.Item>
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Address:
                                </VerifyMessageLabel>
                                <DestinationAddressSingleWithoutQRScan
                                    validateStatus={
                                        messageVerificationAddrError
                                            ? 'error'
                                            : ''
                                    }
                                    help={
                                        messageVerificationAddrError
                                            ? messageVerificationAddrError
                                            : ''
                                    }
                                    inputProps={{
                                        placeholder: `${currency.ticker} Address`,
                                        name: 'address',
                                        onChange: e =>
                                            handleMessageVerificationAddrChange(
                                                e,
                                            ),
                                        required: true,
                                    }}
                                ></DestinationAddressSingleWithoutQRScan>
                            </Form.Item>
                            <Form.Item>
                                <VerifyMessageLabel>
                                    Signature:
                                </VerifyMessageLabel>
                                <TextArea
                                    name="verifySignature"
                                    onChange={e => handleVerifySigChange(e)}
                                    showCount
                                />
                                <SignatureValidation>
                                    {messageVerificationSigError}
                                </SignatureValidation>
                            </Form.Item>
                            <SmartButton
                                onClick={() => setShowConfirmMsgToVerify(true)}
                                disabled={
                                    !messageVerificationAddrIsValid ||
                                    !messageVerificationSigIsValid ||
                                    !messageVerificationMsgIsValid
                                }
                            >
                                <PlusSquareOutlined />
                                 Verify Message
                            </SmartButton>
                        </Form>
                    </AntdFormWrapper>
                </CustomCollapseCtn>
            </SidePaddingCtn>
        </Wrapper>
    );
};

SignVerifyMsg.propTypes = {
    jestBCH: PropTypes.object,
    cashtabSettings: PropTypes.oneOfType([
        PropTypes.shape({
            fiatCurrency: PropTypes.string,
            sendModal: PropTypes.bool,
            autoCameraOn: PropTypes.bool,
            hideMessagesFromUnknownSender: PropTypes.bool,
            toggleShowHideBalance: PropTypes.bool,
        }),
        PropTypes.bool,
    ]),
    changeCashtabSettings: PropTypes.func,
};

export default SignVerifyMsg;
<|endoftext|>


<commit_before>'use strict';

var EE = require('events').EventEmitter;
var util = require('util');

var DATABITS = [7, 8];
var STOPBITS = [1, 2];
var PARITY = ['none', 'even', 'mark', 'odd', 'space'];
var FLOWCONTROLS = ["RTSCTS"];

var _options = {
  baudrate: 9600,
  parity: 'none',
  rtscts: false,
  databits: 8,
  stopbits: 1,
  buffersize: 256
};

function convertOptions(options){
  switch (options.dataBits) {
    case 7:
      options.dataBits = 'seven';
      break;
    case 8:
      options.dataBits = 'eight';
      break;
  }

  switch (options.stopBits) {
    case 1:
      options.stopBits = 'one';
      break;
    case 2:
      options.stopBits = 'two';
      break;
  }

  switch (options.parity) {
    case 'none':
      options.parity = 'no';
      break;
  }

  return options;
}

function SerialPort(path, options, openImmediately, callback) {

  EE.call(this);

  var self = this;

  var args = Array.prototype.slice.call(arguments);
  callback = args.pop();
  if (typeof(callback) !== 'function') {
    callback = null;
  }

  options = (typeof options !== 'function') && options || {};

  openImmediately = (openImmediately === undefined || openImmediately === null) ? true : openImmediately;

  callback = callback || function (err) {
    if (err) {
      self.emit('error', err);
    }
  };

  var err;

  options.baudRate = options.baudRate || options.baudrate || _options.baudrate;

  options.dataBits = options.dataBits || options.databits || _options.databits;
  if (DATABITS.indexOf(options.dataBits) === -1) {
    err = new Error('Invalid "databits": ' + options.dataBits);
    callback(err);
    return;
  }

  options.stopBits = options.stopBits || options.stopbits || _options.stopbits;
  if (STOPBITS.indexOf(options.stopBits) === -1) {
    err = new Error('Invalid "stopbits": ' + options.stopbits);
    callback(err);
    return;
  }

  options.parity = options.parity || _options.parity;
  if (PARITY.indexOf(options.parity) === -1) {
    err = new Error('Invalid "parity": ' + options.parity);
    callback(err);
    return;
  }

  if (!path) {
    err = new Error('Invalid port specified: ' + path);
    callback(err);
    return;
  }

  if (options.flowControl || options.flowcontrol) {
    var fc = options.flowControl || options.flowcontrol;

    if (typeof fc === 'boolean') {
      options.rtscts = true;
    } else {
      fc.forEach(function (flowControl) {
        var fcup = flowControl.toUpperCase();
        var idx = FLOWCONTROLS.indexOf(fcup);
        if (idx < 0) {
          var err = new Error('Invalid "flowControl": ' + fcup + ". Valid options: " + FLOWCONTROLS.join(", "));
          callback(err);
          return;
        } else {

          // "XON", "XOFF", "XANY", "DTRDTS", "RTSCTS"
          switch (idx) {
            case 0: options.rtscts = true; break;
          }
        }
      });
    }
  }

  options.bufferSize = options.bufferSize || options.buffersize || _options.buffersize;

  // defaults to chrome.serial if no options.serial passed
  // inlined instead of on _options to allow mocking global chrome.serial for optional options test
  options.serial = options.serial || (typeof chrome !== 'undefined' && chrome.serial);

  if (!options.serial) {
    throw new Error('No access to serial ports. Try loading as a Chrome Application.');
  }

  this.options = convertOptions(options);

  this.options.serial.onReceiveError.addListener(function(info){

    switch (info.error) {

      case "disconnected":
      case "device_lost":
      case "system_error":
        err = new Error("Disconnected");
        // send notification of disconnect
        if (self.options.disconnectedCallback) {
          self.options.disconnectedCallback(err);
        } else {
          self.emit("disconnect", err);
        }
        self.connectionId = -1;
        self.emit("close");
        self.removeAllListeners();
        break;
      case "timeout":
        break;
    }

  });

  this.path = path;

  if (openImmediately) {
    process.nextTick(function () {
      self.open(callback);
    });
  }
}

util.inherits(SerialPort, EE);

SerialPort.prototype.connectionId = -1;

SerialPort.prototype.open = function (callback) {
  var options = {
    bitrate: parseInt(this.options.baudrate, 10),
    dataBits: this.options.databits,
    parityBit: this.options.parity,
    stopBits: this.options.stopbits,
    ctsFlowControl: this.options.rtscts
  };

  this.options.serial.connect(this.path, options, this.proxy('onOpen', callback));
};

SerialPort.prototype.onOpen = function (callback, openInfo) {

  this.connectionId = openInfo.connectionId;
  if (this.connectionId == -1) {
    this.emit('error', new Error('Could not open port.'));
    return;
  }

  this.emit('open', openInfo);

  typeof callback == 'function' && callback(chrome.runtime.lastError, openInfo);

  this.options.serial.onReceive.addListener(this.proxy('onRead'));
};

SerialPort.prototype.onRead = function (readInfo) {
  if (readInfo && this.connectionId == readInfo.connectionId) {

    if(this.options.dataCallback){
      this.options.dataCallback(toBuffer(readInfo.data));
    }else{
      this.emit('data', toBuffer(readInfo.data));
    }

  }
}

SerialPort.prototype.write = function (buffer, callback) {
  if (typeof callback != 'function') { callback = function() {}; }

  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  if(typeof buffer  === 'string'){
    buffer = str2ab(buffer);
  }

  //Make sure its not a browserify faux Buffer.
  if (buffer instanceof ArrayBuffer == false) {
    buffer = buffer2ArrayBuffer(buffer);
  }

  this.options.serial.send(this.connectionId, buffer, function(info){
    callback(chrome.runtime.lastError, info);
  });
};

SerialPort.prototype.close = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  this.options.serial.disconnect(this.connectionId, this.proxy('onClose', callback));
};

SerialPort.prototype.onClose = function (callback, result) {
  this.connectionId = -1;
  this.emit('close');

  this.removeAllListeners();

  typeof callback == 'function' && callback(chrome.runtime.lastError, result);
};

SerialPort.prototype.flush = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  this.options.serial.flush(this.connectionId, function(err){
    if (err) {
      if (callback) {
        callback(err, result);
      } else {
        self.emit('error', err);
      }
    } else {
      callback(err, result);
    }
  });

};

SerialPort.prototype.drain = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  callback();
};

SerialPort.prototype.proxy = function () {
  var self = this;
  var proxyArgs = [];

  //arguments isnt actually an array.
  for (var i = 0; i < arguments.length; i++) {
      proxyArgs[i] = arguments[i];
  }

  var functionName = proxyArgs.splice(0, 1)[0];

  var func = function() {
    var funcArgs = [];
    for (var i = 0; i < arguments.length; i++) {
        funcArgs[i] = arguments[i];
    }
    var allArgs = proxyArgs.concat(funcArgs);

    self[functionName].apply(self, allArgs);
  }

  return func;
}

SerialPort.prototype.set = function (options, callback) {
  this.options.serial.setControlSignals(this.connectionId, options, function(result){
    callback(chrome.runtime.lastError, result);
  });
};

function SerialPortList(callback) {
  if (typeof chrome != 'undefined' && chrome.serial) {
    chrome.serial.getDevices(function(ports) {
      var portObjects = Array(ports.length);
      for (var i = 0; i < ports.length; i++) {
        portObjects[i] = {
          comName: ports[i].path,
          manufacturer: ports[i].displayName,
          serialNumber: '',
          pnpId: '',
          locationId:'',
          vendorId: "0x" + (ports[i].vendorId||0).toString(16),
          productId: "0x" + (ports[i].productId||0).toString(16)
        };
      }
      callback(chrome.runtime.lastError, portObjects);
    });
  } else {
    callback('No access to serial ports. Try loading as a Chrome Application.', null);
  }
}

// Convert string to ArrayBuffer
function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

// Convert buffer to ArrayBuffer
function buffer2ArrayBuffer(buffer) {
  var buf = new ArrayBuffer(buffer.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0; i < buffer.length; i++) {
    bufView[i] = buffer[i];
  }
  return buf;
}

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      buffer[i] = view[i];
  }
  return buffer;
}

module.exports = {
  SerialPort: SerialPort,
  list: SerialPortList,
  buffer2ArrayBuffer: buffer2ArrayBuffer,
  used: [] //TODO: Populate this somewhere.
};
<commit_msg>another error string<commit_after>'use strict';

var EE = require('events').EventEmitter;
var util = require('util');

var DATABITS = [7, 8];
var STOPBITS = [1, 2];
var PARITY = ['none', 'even', 'mark', 'odd', 'space'];
var FLOWCONTROLS = ["RTSCTS"];

var _options = {
  baudrate: 9600,
  parity: 'none',
  rtscts: false,
  databits: 8,
  stopbits: 1,
  buffersize: 256
};

function convertOptions(options){
  switch (options.dataBits) {
    case 7:
      options.dataBits = 'seven';
      break;
    case 8:
      options.dataBits = 'eight';
      break;
  }

  switch (options.stopBits) {
    case 1:
      options.stopBits = 'one';
      break;
    case 2:
      options.stopBits = 'two';
      break;
  }

  switch (options.parity) {
    case 'none':
      options.parity = 'no';
      break;
  }

  return options;
}

function SerialPort(path, options, openImmediately, callback) {

  EE.call(this);

  var self = this;

  var args = Array.prototype.slice.call(arguments);
  callback = args.pop();
  if (typeof(callback) !== 'function') {
    callback = null;
  }

  options = (typeof options !== 'function') && options || {};

  openImmediately = (openImmediately === undefined || openImmediately === null) ? true : openImmediately;

  callback = callback || function (err) {
    if (err) {
      self.emit('error', err);
    }
  };

  var err;

  options.baudRate = options.baudRate || options.baudrate || _options.baudrate;

  options.dataBits = options.dataBits || options.databits || _options.databits;
  if (DATABITS.indexOf(options.dataBits) === -1) {
    err = new Error('Invalid "databits": ' + options.dataBits);
    callback(err);
    return;
  }

  options.stopBits = options.stopBits || options.stopbits || _options.stopbits;
  if (STOPBITS.indexOf(options.stopBits) === -1) {
    err = new Error('Invalid "stopbits": ' + options.stopbits);
    callback(err);
    return;
  }

  options.parity = options.parity || _options.parity;
  if (PARITY.indexOf(options.parity) === -1) {
    err = new Error('Invalid "parity": ' + options.parity);
    callback(err);
    return;
  }

  if (!path) {
    err = new Error('Invalid port specified: ' + path);
    callback(err);
    return;
  }

  if (options.flowControl || options.flowcontrol) {
    var fc = options.flowControl || options.flowcontrol;

    if (typeof fc === 'boolean') {
      options.rtscts = true;
    } else {
      fc.forEach(function (flowControl) {
        var fcup = flowControl.toUpperCase();
        var idx = FLOWCONTROLS.indexOf(fcup);
        if (idx < 0) {
          var err = new Error('Invalid "flowControl": ' + fcup + ". Valid options: " + FLOWCONTROLS.join(", "));
          callback(err);
          return;
        } else {

          // "XON", "XOFF", "XANY", "DTRDTS", "RTSCTS"
          switch (idx) {
            case 0: options.rtscts = true; break;
          }
        }
      });
    }
  }

  options.bufferSize = options.bufferSize || options.buffersize || _options.buffersize;

  // defaults to chrome.serial if no options.serial passed
  // inlined instead of on _options to allow mocking global chrome.serial for optional options test
  options.serial = options.serial || (typeof chrome !== 'undefined' && chrome.serial);

  if (!options.serial) {
    throw new Error('No access to serial ports. Try loading as a Chrome Application.');
  }

  this.options = convertOptions(options);

  this.options.serial.onReceiveError.addListener(function(info){

    switch (info.error) {

      case "disconnected":
      case "device_lost":
      case "system_error":
        err = new Error("Disconnected");
        // send notification of disconnect
        if (self.options.disconnectedCallback) {
          self.options.disconnectedCallback(err);
        } else {
          self.emit("disconnect", err);
        }
        self.connectionId = -1;
        self.emit("close");
        self.removeAllListeners();
        break;
      case "timeout":
        break;
    }

  });

  this.path = path;

  if (openImmediately) {
    process.nextTick(function () {
      self.open(callback);
    });
  }
}

util.inherits(SerialPort, EE);

SerialPort.prototype.connectionId = -1;

SerialPort.prototype.open = function (callback) {
  var options = {
    bitrate: parseInt(this.options.baudrate, 10),
    dataBits: this.options.databits,
    parityBit: this.options.parity,
    stopBits: this.options.stopbits,
    ctsFlowControl: this.options.rtscts
  };

  this.options.serial.connect(this.path, options, this.proxy('onOpen', callback));
};

SerialPort.prototype.onOpen = function (callback, openInfo) {

  this.connectionId = openInfo.connectionId;
  if (this.connectionId == -1) {
    this.emit('error', new Error('Could not open port.'));
    return;
  }

  this.emit('open', openInfo);

  typeof callback == 'function' && callback(chrome.runtime.lastError, openInfo);

  this.options.serial.onReceive.addListener(this.proxy('onRead'));
};

SerialPort.prototype.onRead = function (readInfo) {
  if (readInfo && this.connectionId == readInfo.connectionId) {

    if(this.options.dataCallback){
      this.options.dataCallback(toBuffer(readInfo.data));
    }else{
      this.emit('data', toBuffer(readInfo.data));
    }

  }
}

SerialPort.prototype.write = function (buffer, callback) {
  if (typeof callback != 'function') { callback = function() {}; }

  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  if(typeof buffer  === 'string'){
    buffer = str2ab(buffer);
  }

  //Make sure its not a browserify faux Buffer.
  if (buffer instanceof ArrayBuffer == false) {
    buffer = buffer2ArrayBuffer(buffer);
  }

  this.options.serial.send(this.connectionId, buffer, function(info){
    callback(chrome.runtime.lastError, info);
  });
};

SerialPort.prototype.close = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  this.options.serial.disconnect(this.connectionId, this.proxy('onClose', callback));
};

SerialPort.prototype.onClose = function (callback, result) {
  this.connectionId = -1;
  this.emit('close');

  this.removeAllListeners();

  typeof callback == 'function' && callback(chrome.runtime.lastError, result);
};

SerialPort.prototype.flush = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  this.options.serial.flush(this.connectionId, function(err){
    if (err) {
      if (callback) {
        callback(err, result);
      } else {
        self.emit('error', err);
      }
    } else {
      callback(err, result);
    }
  });

};

SerialPort.prototype.drain = function (callback) {
  if ( this.connectionId<0 ) { return callback(new Error("Serialport not open.")); }

  callback();
};

SerialPort.prototype.proxy = function () {
  var self = this;
  var proxyArgs = [];

  //arguments isnt actually an array.
  for (var i = 0; i < arguments.length; i++) {
      proxyArgs[i] = arguments[i];
  }

  var functionName = proxyArgs.splice(0, 1)[0];

  var func = function() {
    var funcArgs = [];
    for (var i = 0; i < arguments.length; i++) {
        funcArgs[i] = arguments[i];
    }
    var allArgs = proxyArgs.concat(funcArgs);

    self[functionName].apply(self, allArgs);
  }

  return func;
}

SerialPort.prototype.set = function (options, callback) {
  this.options.serial.setControlSignals(this.connectionId, options, function(result){
    callback(chrome.runtime.lastError, result);
  });
};

function SerialPortList(callback) {
  if (typeof chrome != 'undefined' && chrome.serial) {
    chrome.serial.getDevices(function(ports) {
      var portObjects = Array(ports.length);
      for (var i = 0; i < ports.length; i++) {
        portObjects[i] = {
          comName: ports[i].path,
          manufacturer: ports[i].displayName,
          serialNumber: '',
          pnpId: '',
          locationId:'',
          vendorId: "0x" + (ports[i].vendorId||0).toString(16),
          productId: "0x" + (ports[i].productId||0).toString(16)
        };
      }
      callback(chrome.runtime.lastError, portObjects);
    });
  } else {
    callback(new Error('No access to serial ports. Try loading as a Chrome Application.'), null);
  }
}

// Convert string to ArrayBuffer
function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0; i < str.length; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

// Convert buffer to ArrayBuffer
function buffer2ArrayBuffer(buffer) {
  var buf = new ArrayBuffer(buffer.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0; i < buffer.length; i++) {
    bufView[i] = buffer[i];
  }
  return buf;
}

function toBuffer(ab) {
  var buffer = new Buffer(ab.byteLength);
  var view = new Uint8Array(ab);
  for (var i = 0; i < buffer.length; ++i) {
      buffer[i] = view[i];
  }
  return buffer;
}

module.exports = {
  SerialPort: SerialPort,
  list: SerialPortList,
  buffer2ArrayBuffer: buffer2ArrayBuffer,
  used: [] //TODO: Populate this somewhere.
};
<|endoftext|>


<commit_before>'use strict';

const getSetMembersInfo = require('../../db/redis.js').getSetMembersInfo;
const filterHarnessTalent = require('../utils/app.js').filterHarnessTalent;

const cleanPayload = require('../utils/app.js').cleanPayload;
const interviewSchema = require('../utils/joiSchema.js').interviewSchema;
const client = require('../../db/client.js');
const getInterviewDetails = require('../../db/redis/getInterviewDetails.js');
const moveToNextInterviewStage = require('../../db/redis/moveToNextInterviewStage');
const uuid = require('uuid');

const fs = require('fs');
const changeInterview = require('../utils/mailgun.js').changeInterview;
const interviewConfirmation = require('../utils/mailgun.js').interviewConfirmation;
const proposedInterview = require('../utils/mailgun.js').proposedInterview;

const mailgun = require('../utils/mailgun.js');

exports.register = (server, options, next) => {

    server.route(
        [{
                method: 'GET',
                path: '/harnesstalent',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                    },
                    handler: (request, reply) => {
                        reply.file('./public/views/harnesstalent.html')
                    }

                }
            }, {
                method: 'GET',
                path: '/harnesstalent/results',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                    },
                    handler: (request, reply) => {
                        let query = request.query
                        console.log('QUERY >>>>>>>>>>>>>', query);
                        let set = 'HarnessTalent';
                        let response = {};
                        response.userType = request.auth.type;

                        if (response.userType !== 'client') {
                            response.userType = 'admin';
                        }
                        getSetMembersInfo(set, (harnessTalentList) => {

                            if (Object.keys(harnessTalentList).length === 0 || Object.keys(query).length === 0) {
                                console.log('Initial Render and no query Render', Object.keys(harnessTalentList), query);
                                response.array = harnessTalentList;
                                reply(response);

                            } else {

                                let filterKeys = findKeysWithoutValueAll(query);
                                console.log('FK', filterKeys);

                                let filterKeyExcSalary = removeSalaryMinMax(filterKeys);

                                // if all queris are 'All';
                                if (filterKeys.length === 0) {
                                    response.array = harnessTalentList
                                    return reply(response);
                                }

                                // salary Max
                                if (filterKeyExcSalary.length === 0 && query.salaryMax !== 'All' && query.salaryMin === 'All') {

                                    let candidatesFilteredOnlyMax = filterBySalaryMax(harnessTalentList, query);
                                    response.array = candidatesFilteredOnlyMax;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0 && query.salaryMax !== 'All' && query.salaryMin === 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candidatesFilteredOnlyMax = filterBySalaryMax(candidatesFilteredExcSalary, query);
                                    response.array = candidatesFilteredOnlyMax;
                                    return reply(response);
                                }

                                // salary Min
                                if (filterKeyExcSalary.length === 0 && query.salaryMin !== 'All' && query.salaryMax === 'All') {

                                    let candidatesFilteredOnlyMin = filterBySalaryMin(harnessTalentList, query);
                                    response.array = candidatesFilteredOnlyMin;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0 && query.salaryMax === 'All' && query.salaryMin !== 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candidatesFilteredOnlyMin = filterBySalaryMin(candidatesFilteredExcSalary, query);
                                    response.array = candidatesFilteredOnlyMin
                                    return reply(response);
                                }

                                // salary Range

                                if (filterKeyExcSalary.length === 0 && query.salaryMin !== 'All' && query.salaryMax !== 'All') {
                                    let candidatesFilteredByRange = filterBySalaryRange(harnessTalentList, query);
                                    response.array = candidatesFilteredByRange;
                                    return reply(response);
                                }

                                if (filterKeys.length > 0 && query.salaryMin !== 'All' && query.salaryMax !== 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candiatesFilteredByRange = filterBySalaryRange(candidatesFilteredExcSalary, query);
                                    response.array = candiatesFilteredByRange;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0) {
                                    let candidatesFiltered = harnessTalentList.filter(checkCandidate);
                                    response.array = candidatesFiltered;
                                    return reply(response);

                                }

                                function findKeysWithoutValueAll(query) {
                                    let filterKeys = Object.keys(query).filter((key) => {
                                        return query[key] !== 'All'
                                    });
                                    return filterKeys;
                                }

                                function removeSalaryMinMax(keys) {
                                    let lessMinMax = keys.filter((ele) => {
                                        return ele !== 'salaryMin' && ele !== 'salaryMax';
                                    })
                                    return lessMinMax;
                                }

                                function checkCandidate(candidate) {
                                    for (var i = 0; i < filterKeyExcSalary.length; i++) {
                                        return candidate[filterKeyExcSalary[i]] === query[filterKeyExcSalary[i]] &&
                                            candidate[filterKeyExcSalary[i + 1]] === query[filterKeyExcSalary[i + 1]] &&
                                            candidate[filterKeyExcSalary[i + 2]] === query[filterKeyExcSalary[i + 2]] &&
                                            candidate[filterKeyExcSalary[i + 3]] === query[filterKeyExcSalary[i + 3]] &&
                                            candidate[filterKeyExcSalary[i + 4]] === query[filterKeyExcSalary[i + 4]]
                                    }
                                }

                                let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);

                                function filterBySalaryMax(array, query) {
                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = candidate.salary.split('£')[1].replace(/\,/g, '');
                                        salary = parseInt(salary);
                                        return salary <= query.salaryMax
                                    })

                                    return candidatesFiltered;
                                }

                                let candidatesFilteredOnlyMax = filterBySalaryMax(candidatesFilteredExcSalary, query);

                                function filterBySalaryMin(array, query) {
                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = candidate.salary.split('£')[1].replace(/\,/g, '');
                                        salary = parseInt(salary);
                                        return salary >= query.salaryMin
                                    })

                                    return candidatesFiltered;
                                }

                                let candidatesFilteredOnlyMin = filterBySalaryMin(candidatesFilteredExcSalary, query);

                                function filterBySalaryRange(array, query) {

                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = candidate.salary.split('£')[1].replace(/\,/g, '');
                                        salary = parseInt(salary);
                                        return salary >= query.salaryMin && salary <= query.salaryMax;
                                    })
                                    return candidatesFiltered;
                                }

                            }

                        });
                    }
                }

            }, {
                method: 'POST',
                path: '/harnesstalent/interview/proposed',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                            // scope: ['client', 'agent']
                    },
                    validate: {
                        payload: interviewSchema
                    },
                    handler: (request, reply) => {
                        ///  must update stage in db;
                        const newTimes = request.payload;
                        const clientId = request.auth.credentials.profile.id;
                        console.log(clientId);

                        const interviewId = uuid.v1() + 'interviewId';
                        newTimes.interviewId = interviewId;
                        newTimes.confirmed = false;

                        /// get the agency email and then send an email with a link to the agency with proposed
                        // job title and salary also link back to interview page. need to create interview hash include in link
                        let agencyId = newTimes.agencyId;
                        let cvid = newTimes.cvid;

                        client.hgetAsync(agencyId, 'email')
                            .then((agencyEmail) => {
                                newTimes.agencyEmail = agencyEmail;

                                client.hgetAsync(clientId, 'companyName')
                                    .then((clientCompanyName) => {
                                        newTimes.clientCompanyName = clientCompanyName;

                                        let newProposedInterview = Object.assign({}, proposedInterview);

                                        newProposedInterview.html = newProposedInterview.html
                                            .replace('-candidateName-', newTimes.candidateName)
                                            .replace('-jobTitle-', newTimes.jobTitle) //switch to client jobTitle.
                                            .replace('-companyName-', newTimes.clientCompanyName)
                                            .replace('-interviewId-', newTimes.interviewId);

                                        newProposedInterview.to = agencyEmail;
                                        mailgun.messages().send(newProposedInterview)

                                    })
                                    .then(() => {
                                        console.log('>>>>>>>>>>>>', interviewId , newTimes);
                                        let interview = cleanPayload(newTimes);
                                        client.hincrby(cvid, 'interviewsRequested',1);
                                        client.hmsetAsync(interviewId, interview);
                                    })
                                    .then(() => {
                                        return reply(cvid);
                                    })
                                    .catch(() => {
                                        return reply(false)
                                    });
                            })
                    }
                }
            }

        ]);
    return next();
};

exports.register.attributes = {
    name: 'Clientharnesstalent'
};
<commit_msg>convert salary to number<commit_after>'use strict';

const getSetMembersInfo = require('../../db/redis.js').getSetMembersInfo;
const filterHarnessTalent = require('../utils/app.js').filterHarnessTalent;

const cleanPayload = require('../utils/app.js').cleanPayload;
const interviewSchema = require('../utils/joiSchema.js').interviewSchema;
const client = require('../../db/client.js');
const getInterviewDetails = require('../../db/redis/getInterviewDetails.js');
const moveToNextInterviewStage = require('../../db/redis/moveToNextInterviewStage');
const uuid = require('uuid');

const fs = require('fs');
const changeInterview = require('../utils/mailgun.js').changeInterview;
const interviewConfirmation = require('../utils/mailgun.js').interviewConfirmation;
const proposedInterview = require('../utils/mailgun.js').proposedInterview;

const mailgun = require('../utils/mailgun.js');

exports.register = (server, options, next) => {

    server.route(
        [{
                method: 'GET',
                path: '/harnesstalent',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                    },
                    handler: (request, reply) => {
                        reply.file('./public/views/harnesstalent.html')
                    }

                }
            }, {
                method: 'GET',
                path: '/harnesstalent/results',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                    },
                    handler: (request, reply) => {
                        let query = request.query
                        console.log('QUERY >>>>>>>>>>>>>', query);
                        let set = 'HarnessTalent';
                        let response = {};
                        response.userType = request.auth.type;

                        if (response.userType !== 'client') {
                            response.userType = 'admin';
                        }
                        getSetMembersInfo(set, (harnessTalentList) => {

                            if (Object.keys(harnessTalentList).length === 0 || Object.keys(query).length === 0) {
                                console.log('Initial Render and no query Render', Object.keys(harnessTalentList), query);
                                response.array = harnessTalentList;
                                reply(response);

                            } else {

                                let filterKeys = findKeysWithoutValueAll(query);

                                let filterKeyExcSalary = removeSalaryMinMax(filterKeys);

                                // if all queris are 'All';
                                if (filterKeys.length === 0) {
                                    response.array = harnessTalentList
                                    return reply(response);
                                }

                                // salary Max
                                if (filterKeyExcSalary.length === 0 && query.salaryMax !== 'All' && query.salaryMin === 'All') {

                                    let candidatesFilteredOnlyMax = filterBySalaryMax(harnessTalentList, query);
                                    response.array = candidatesFilteredOnlyMax;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0 && query.salaryMax !== 'All' && query.salaryMin === 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candidatesFilteredOnlyMax = filterBySalaryMax(candidatesFilteredExcSalary, query);
                                    response.array = candidatesFilteredOnlyMax;
                                    return reply(response);
                                }

                                // salary Min
                                if (filterKeyExcSalary.length === 0 && query.salaryMin !== 'All' && query.salaryMax === 'All') {

                                    let candidatesFilteredOnlyMin = filterBySalaryMin(harnessTalentList, query);
                                    response.array = candidatesFilteredOnlyMin;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0 && query.salaryMax === 'All' && query.salaryMin !== 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candidatesFilteredOnlyMin = filterBySalaryMin(candidatesFilteredExcSalary, query);
                                    response.array = candidatesFilteredOnlyMin
                                    return reply(response);
                                }

                                // salary Range

                                if (filterKeyExcSalary.length === 0 && query.salaryMin !== 'All' && query.salaryMax !== 'All') {
                                    let candidatesFilteredByRange = filterBySalaryRange(harnessTalentList, query);
                                    response.array = candidatesFilteredByRange;
                                    return reply(response);
                                }

                                if (filterKeys.length > 0 && query.salaryMin !== 'All' && query.salaryMax !== 'All') {
                                    let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);
                                    let candiatesFilteredByRange = filterBySalaryRange(candidatesFilteredExcSalary, query);
                                    response.array = candiatesFilteredByRange;
                                    return reply(response);
                                }

                                if (filterKeyExcSalary.length > 0) {
                                    let candidatesFiltered = harnessTalentList.filter(checkCandidate);
                                    response.array = candidatesFiltered;
                                    return reply(response);

                                }
                                let candidatesFilteredExcSalary = harnessTalentList.filter(checkCandidate);

                                let candidatesFilteredOnlyMax = filterBySalaryMax(candidatesFilteredExcSalary, query);

                                let candidatesFilteredOnlyMin = filterBySalaryMin(candidatesFilteredExcSalary, query);

                                function findKeysWithoutValueAll(query) {
                                    let filterKeys = Object.keys(query).filter((key) => {
                                        return query[key] !== 'All'
                                    });
                                    return filterKeys;
                                }

                                function removeSalaryMinMax(keys) {
                                    let lessMinMax = keys.filter((ele) => {
                                        return ele !== 'salaryMin' && ele !== 'salaryMax';
                                    })
                                    return lessMinMax;
                                }

                                function checkCandidate(candidate) {
                                    for (var i = 0; i < filterKeyExcSalary.length; i++) {
                                        return candidate[filterKeyExcSalary[i]] === query[filterKeyExcSalary[i]] &&
                                            candidate[filterKeyExcSalary[i + 1]] === query[filterKeyExcSalary[i + 1]] &&
                                            candidate[filterKeyExcSalary[i + 2]] === query[filterKeyExcSalary[i + 2]] &&
                                            candidate[filterKeyExcSalary[i + 3]] === query[filterKeyExcSalary[i + 3]] &&
                                            candidate[filterKeyExcSalary[i + 4]] === query[filterKeyExcSalary[i + 4]]
                                    }
                                }

                                function convertSalaryToNumber(salaryString){
                                    let salary = salaryString.split('£')[1].replace(/\,/g, '');
                                    salary = parseInt(salary);
                                    return salary;
                                }

                                function filterBySalaryMax(array, query) {
                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = convertSalaryToNumber(candidate.salary);
                                        return salary <= query.salaryMax
                                    });
                                    return candidatesFiltered;
                                }

                                function filterBySalaryMin(array, query) {
                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = convertSalaryToNumber(candidate.salary);
                                        return salary >= query.salaryMin
                                    })

                                    return candidatesFiltered;
                                }

                                function filterBySalaryRange(array, query) {
                                    let candidatesFiltered = array.filter((candidate) => {
                                        let salary = convertSalaryToNumber(candidate.salary);
                                        return salary >= query.salaryMin && salary <= query.salaryMax;
                                    })
                                    return candidatesFiltered;
                                }

                            }

                        });
                    }
                }

            }, {
                method: 'POST',
                path: '/harnesstalent/interview/proposed',
                config: {
                    auth: {
                        strategy: 'hrns-cookie'
                            // scope: ['client', 'agent']
                    },
                    validate: {
                        payload: interviewSchema
                    },
                    handler: (request, reply) => {
                        ///  must update stage in db;
                        const newTimes = request.payload;
                        const clientId = request.auth.credentials.profile.id;
                        console.log(clientId);

                        const interviewId = uuid.v1() + 'interviewId';
                        newTimes.interviewId = interviewId;
                        newTimes.confirmed = false;

                        /// get the agency email and then send an email with a link to the agency with proposed
                        // job title and salary also link back to interview page. need to create interview hash include in link
                        let agencyId = newTimes.agencyId;
                        let cvid = newTimes.cvid;

                        client.hgetAsync(agencyId, 'email')
                            .then((agencyEmail) => {
                                newTimes.agencyEmail = agencyEmail;

                                client.hgetAsync(clientId, 'companyName')
                                    .then((clientCompanyName) => {
                                        newTimes.clientCompanyName = clientCompanyName;

                                        let newProposedInterview = Object.assign({}, proposedInterview);

                                        newProposedInterview.html = newProposedInterview.html
                                            .replace('-candidateName-', newTimes.candidateName)
                                            .replace('-jobTitle-', newTimes.jobTitle) //switch to client jobTitle.
                                            .replace('-companyName-', newTimes.clientCompanyName)
                                            .replace('-interviewId-', newTimes.interviewId);

                                        newProposedInterview.to = agencyEmail;
                                        mailgun.messages().send(newProposedInterview)

                                    })
                                    .then(() => {
                                        console.log('>>>>>>>>>>>>', interviewId , newTimes);
                                        let interview = cleanPayload(newTimes);
                                        client.hincrby(cvid, 'interviewsRequested',1);
                                        client.hmsetAsync(interviewId, interview);
                                    })
                                    .then(() => {
                                        return reply(cvid);
                                    })
                                    .catch(() => {
                                        return reply(false)
                                    });
                            })
                    }
                }
            }

        ]);
    return next();
};

exports.register.attributes = {
    name: 'Clientharnesstalent'
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    const store = this.store;

    return store.find('tournament', params.tournamentId);
  },

  setupController(controller, model, transition) {
    this._super(controller, model, transition);

    controller.set('status', model.get('status'));

    this.controllerFor('application').addObserver('currentPath', this, this.currentPathChanged);
  },

  currentPathChanged(applicationContoller) {
    let currentTournamentsRoute = applicationContoller.get('currentPath').split('.')[2];
    let tabList = ['tablescore', 'matches', 'teams', 'settings'];

    if (0 <= tabList.indexOf(currentTournamentsRoute)) {
      this.controllerFor('tournament').set('selectedTab', currentTournamentsRoute);
    }
  }
});
<commit_msg>Fixed nav tab on tournament team page<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    const store = this.store;

    return store.find('tournament', params.tournamentId);
  },

  setupController(controller, model, transition) {
    this._super(controller, model, transition);

    controller.set('status', model.get('status'));

    this.controllerFor('application').addObserver('currentPath', this, this.currentPathChanged);
  },

  currentPathChanged(applicationContoller) {
    let currentTournamentsRoute = applicationContoller.get('currentPath').split('.')[2];

    // teams and team routes must have one tab
    if (currentTournamentsRoute === 'team') {
      currentTournamentsRoute = 'teams';
    }

    let tabList = ['tablescore', 'matches', 'teams', 'settings'];

    if (0 <= tabList.indexOf(currentTournamentsRoute)) {
      this.controllerFor('tournament').set('selectedTab', currentTournamentsRoute);
    }
  }
});
<|endoftext|>


<commit_before>"use strict";

//const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const gcs = require('@google-cloud/storage')();
const im = require('imagemagick');
const uuidv4 = require('uuid/v4');

// const vision = require('@google-cloud/vision')();

// 'Pixel budget' denotes the maximum amount of pixels in the thumbnail
const PIXEL_BUDGET = 50 * 50;

// convert example:
// `convert`, [`-define`, `jpeg:size=600x400`, tempLocalFile, `-thumbnail`,
// `600x400^`, `-gravity`, `center`, `-extent`, `600x400`, tempLocalThumbFileMedium]

// image size:
// convert larvi.jpg -ping -format "%w x %h" info:

function thumbnailize(imageFilePath, width, height) {
  return new Promise((resolve, reject) => {
    // Calculate the size of the thumbnail
    const origPixels = width * height;
    const ratio = Math.sqrt(PIXEL_BUDGET / origPixels);
    console.log('pixel ratio', ratio);
    const thumbWidth = Math.round(ratio * width);
    const thumbHeight = Math.round(ratio * height);
    console.log('thumb size', thumbWidth, thumbHeight);

    im.resize({
      srcPath: imageFilePath,
      dstPath: imageFilePath,
      quality: 0.3,
      format: 'jpg',
      width: thumbWidth,
      height: thumbHeight
    }, (err) => {
      if (err) {
        return reject(err);
      }

      console.log('Image resized OK!');

      //TODO next step

      //TODO 1. downscale 2. blur 3. extract JPEG data 4. store to output bucket

      // All done
      resolve();
    });

  });
};

function processFile(file) {
  console.log('Processing input file: ', file.name);
// const tempLocalFilename = `/tmp/${path.parse(file.name).base}`;

  return new Promise((resolve, reject) => {
    // Form a local path for the file
    const tempLocalFilename = `/tmp/${uuidv4()}`;
    console.log('tempLocalFilename=', tempLocalFilename);

    // Download file from bucket.
    file.download({destination: tempLocalFilename})
      .catch((err) => {
        console.error('Failed to download file.', err);
        return reject(err);
      })
      .then(() => {
        console.log(`Image ${file.name} downloaded to ${tempLocalFilename}.`);

        // Figure out the image dimensions
        im.identify(tempLocalFilename, (err, features) => {
          if (err) {
            return reject(err);
          }

          // console.log("Image features: ", features);
          // { format: 'JPEG', width: 3904, height: 2622, depth: 8 }

          return thumbnailize(tempLocalFilename, features.width,
            features.height);
        });
      });
  });
}

/**
 * TODO
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.thumbnails = function (event, callback) {
  const object = event.data;

  if (object.resourceState === 'not_exists') {
    console.log(`File ${object.name} deleted.`);
    callback();
  } else if (object.metageneration === '1') {
    // metageneration attribute is updated on metadata changes.
    // on create value is 1
    console.log(`File ${object.name} uploaded.`);

    const file = gcs.bucket(object.bucket).file(object.name);

    processFile(file, callback)
      .then(() => {
        console.log('processFile() completed.');
        callback();
      })
      .catch((err) => {
        console.log('processFile() failed: ', err);
        callback();
      });
  } else {
    console.log(`File ${object.name} metadata updated.`);
    callback();
  }
};
<commit_msg>Added file upload to output bucket.<commit_after>"use strict";

//const exec = require('child_process').exec;
const fs = require('fs');
const path = require('path');
const gcs = require('@google-cloud/storage')();
const im = require('imagemagick');
const uuidv4 = require('uuid/v4');

// const vision = require('@google-cloud/vision')();

// 'Pixel budget' denotes the maximum amount of pixels in the thumbnail
const PIXEL_BUDGET = 50 * 50;

// Our output bucket
const OUTPUT_BUCKET = 'qvik-gcf-thumbnails-output';

// convert example:
// `convert`, [`-define`, `jpeg:size=600x400`, tempLocalFile, `-thumbnail`,
// `600x400^`, `-gravity`, `center`, `-extent`, `600x400`, tempLocalThumbFileMedium]

// image size:
// convert larvi.jpg -ping -format "%w x %h" info:

function thumbnailize(originalFileName, imageFilePath, width, height) {
  console.log('originalFileName=', originalFileName);

  return new Promise((resolve, reject) => {
    // Calculate the size of the thumbnail
    const origPixels = width * height;
    const ratio = Math.sqrt(PIXEL_BUDGET / origPixels);
    console.log('pixel ratio', ratio);
    const thumbWidth = Math.round(ratio * width);
    const thumbHeight = Math.round(ratio * height);
    console.log('thumb size', thumbWidth, thumbHeight);

    im.resize({
      srcPath: imageFilePath,
      dstPath: imageFilePath,
      quality: 0.3,
      format: 'jpg',
      width: thumbWidth,
      height: thumbHeight
    }, (err) => {
      if (err) {
        return reject(err);
      }

      console.log('Image resized OK!');

      //TODO next step

      //TODO 1. downscale 2. blur 3. extract JPEG data 4. store to output bucket

      // Write the file to the output bucket
      const bucket = gcs.bucket(OUTPUT_BUCKET);
     // const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
      const contentType = 'image/jpeg'; //TODO

      const uploadOptions = {
        destination: originalFileName,
        metadata: {contentType: contentType}
      };

      bucket.upload(imageFilePath, uploadOptions, (err) => {
          if (err) {
            return reject(err);
          }

          console.log('File written to output bucket');

          // All done
          console.log("All done!");
          resolve();
        })
    });
  });
};

function processFile(file) {
  console.log('Processing input file:', file.name);
// const tempLocalFilename = `/tmp/${path.parse(file.name).base}`;

  return new Promise((resolve, reject) => {
    // Form a local path for the file
    const tempLocalFilename = `/tmp/${uuidv4()}`;
    console.log('tempLocalFilename=', tempLocalFilename);

    // Download file from bucket.
    file.download({destination: tempLocalFilename})
      .catch((err) => {
        console.error('Failed to download file.', err);
        return reject(err);
      })
      .then(() => {
        console.log(`Image ${file.name} downloaded to ${tempLocalFilename}.`);

        // Figure out the image dimensions
        im.identify(tempLocalFilename, (err, features) => {
          if (err) {
            return reject(err);
          }

          // console.log("Image features: ", features);
          // { format: 'JPEG', width: 3904, height: 2622, depth: 8 }

          return thumbnailize(file.name, tempLocalFilename, features.width,
            features.height);
        });
      });
  });
}

/**
 * TODO
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.thumbnails = function (event, callback) {
  const object = event.data;
  console.log('object', object);

  if (object.resourceState === 'not_exists') {
    console.log(`File ${object.name} deleted.`);
    callback();
  } else if (object.metageneration === '1') {
    // metageneration attribute is updated on metadata changes.
    // on create value is 1
    console.log(`File ${object.name} uploaded.`);

    const file = gcs.bucket(object.bucket).file(object.name);

    processFile(file, callback)
      .then(() => {
        console.log('processFile() completed.');
        callback();
      })
      .catch((err) => {
        console.log('processFile() failed: ', err);
        callback();
      });
  } else {
    console.log(`File ${object.name} metadata updated.`);
    callback();
  }
};
<|endoftext|>


<commit_before>/*
Start this program from the command line with `pm2`

    ~/Nodes/punkish$ NODE_ENV=production pm2 start index.js --name zenodeo
    ~/Nodes/punkish$ NODE_ENV=production pm2 restart zenodeo
*/

'use strict';

//const Config = require('./config.js');
const Hapi = require('hapi');
const Disk = require('catbox-disk');

const config = require('config');
const cacheName = config.get('cache.v2.name');
const cachePath = config.get('cache.path');
const info = config.get('info');
const swaggeredScheme = config.get('swaggered-scheme');
const port = config.get('port')

/*
 * blipp is a simple hapi plugin to display
 * the routes table at startup
 */
const Blipp = require('blipp');

/*
 * Static file and directory handlers for hapi.js
 */
const Inert = require('inert');

/*
 * Template rendering support for hapi.js
 */
const Vision = require('vision');

/*
 * Generate Swagger-compatible documentation for the app
 */
console.log(Config.schemes)
const HapiSwagger = require('hapi-swagger');
const swaggerOptions = {
    documentationPage: false,
    documentationPath: "/docs",
    info: info,
    sortEndpoints: 'ordered',
    jsonEditor: false,
<<<<<<< HEAD
    validatorUrl: null
    //schemes: Config.schemes
=======
    validatorUrl: null,
    schemes: swaggeredScheme
>>>>>>> blr
};

/*
 * Hapi process monitoring
 */
const Good = require('good');
const goodOptions = {
    ops: {
        interval: 1000
    },
    reporters: {
        console: [
            {
                module: 'good-squeeze',
                name: 'Squeeze',
                args: [{ log: '*', response: 'api' }]
            },
            {
                module: 'good-console',
                args: [{ format: 'MMM Do YYYY, h:mm:ss A' }]
            },
            'stdout'
        ]
    }
};

const Debug = require('debug')('server: index')

const server = new Hapi.server({
    port: port,
    host: 'localhost',
    routes: { cors: true },
    cache: [{
		name: cacheName,
		engine: new Disk({
            cachePath: cachePath,
            cleanEvery: 0,
            partition: 'cache'
        })
    }],
    router: {
        stripTrailingSlash: true
    }
});

const start = async () => {

    await server.register([
        { plugin: Inert, options: {} },
        { plugin: Vision, options: {} },
        { plugin: Blipp, options: {} } ,
        { plugin: Good, options: goodOptions },
        { plugin: HapiSwagger, options: swaggerOptions },
        { plugin: require('./api/v1/index.js'), routes: { prefix: '/v1' } },
        { plugin: require('./api/v2/index.js'), routes: { prefix: '/v2' } }
    ]);

    server.views({
        engines: {
            html: require('handlebars')
        },
        relativeTo: __dirname,
        path: './views',
        layoutPath: './views/layouts',
        partialsPath: './views/partials',
        layout: 'main',
        isCached: false
    });

    server.route([
        require('./resources/inert'),
        require('./resources/docs'),
        require('./resources/tos'),
        require('./resources/install'),
        require('./resources/examples'),
        require('./resources/about')
    ]);

    await server.start();
    Debug(`Server running at: ${server.info.uri}`);
};

start();<commit_msg>fixed merge error<commit_after>/*
Start this program from the command line with `pm2`

    ~/Nodes/punkish$ NODE_ENV=production pm2 start index.js --name zenodeo
    ~/Nodes/punkish$ NODE_ENV=production pm2 restart zenodeo
*/

'use strict';

//const Config = require('./config.js');
const Hapi = require('hapi');
const Disk = require('catbox-disk');

const config = require('config');
const cacheName = config.get('cache.v2.name');
const cachePath = config.get('cache.path');
const info = config.get('info');
const swaggeredScheme = config.get('swaggered-scheme');
const port = config.get('port')

/*
 * blipp is a simple hapi plugin to display
 * the routes table at startup
 */
const Blipp = require('blipp');

/*
 * Static file and directory handlers for hapi.js
 */
const Inert = require('inert');

/*
 * Template rendering support for hapi.js
 */
const Vision = require('vision');

/*
 * Generate Swagger-compatible documentation for the app
 */
//console.log(Config.schemes)
const HapiSwagger = require('hapi-swagger');
const swaggerOptions = {
    documentationPage: false,
    documentationPath: "/docs",
    info: info,
    sortEndpoints: 'ordered',
    jsonEditor: false,
    validatorUrl: null,
    schemes: swaggeredScheme
};

/*
 * Hapi process monitoring
 */
const Good = require('good');
const goodOptions = {
    ops: {
        interval: 1000
    },
    reporters: {
        console: [
            {
                module: 'good-squeeze',
                name: 'Squeeze',
                args: [{ log: '*', response: 'api' }]
            },
            {
                module: 'good-console',
                args: [{ format: 'MMM Do YYYY, h:mm:ss A' }]
            },
            'stdout'
        ]
    }
};

const Debug = require('debug')('server: index')

const server = new Hapi.server({
    port: port,
    host: 'localhost',
    routes: { cors: true },
    cache: [{
		name: cacheName,
		engine: new Disk({
            cachePath: cachePath,
            cleanEvery: 0,
            partition: 'cache'
        })
    }],
    router: {
        stripTrailingSlash: true
    }
});

const start = async () => {

    await server.register([
        { plugin: Inert, options: {} },
        { plugin: Vision, options: {} },
        { plugin: Blipp, options: {} } ,
        { plugin: Good, options: goodOptions },
        { plugin: HapiSwagger, options: swaggerOptions },
        { plugin: require('./api/v1/index.js'), routes: { prefix: '/v1' } },
        { plugin: require('./api/v2/index.js'), routes: { prefix: '/v2' } }
    ]);

    server.views({
        engines: {
            html: require('handlebars')
        },
        relativeTo: __dirname,
        path: './views',
        layoutPath: './views/layouts',
        partialsPath: './views/partials',
        layout: 'main',
        isCached: false
    });

    server.route([
        require('./resources/inert'),
        require('./resources/docs'),
        require('./resources/tos'),
        require('./resources/install'),
        require('./resources/examples'),
        require('./resources/about')
    ]);

    await server.start();
    Debug(`Server running at: ${server.info.uri}`);
};

start();<|endoftext|>