Add TOR loading component

This commit is contained in:
Reckless_Satoshi 2023-02-20 07:19:17 -08:00
parent 04abffee44
commit b98c7a1e9f
No known key found for this signature in database
GPG Key ID: 9C4585B561315571
6 changed files with 534 additions and 81 deletions

View File

@ -4,7 +4,7 @@ import Main from './basic/Main';
import { CssBaseline } from '@mui/material';
import { ThemeProvider, createTheme, Theme } from '@mui/material/styles';
import UnsafeAlert from './components/UnsafeAlert';
import TorConnection from './components/TorConnection';
import TorConnectionBadge from './components/TorConnection';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n/Web';
@ -29,6 +29,13 @@ const makeTheme = function (settings: Settings) {
const App = (): JSX.Element => {
const [theme, setTheme] = useState<Theme>(makeTheme(new Settings()));
const [settings, setSettings] = useState<Settings>(new Settings());
const [torStatus, setTorStatus] = useState<string>('NOTINIT');
useEffect(() => {
window.addEventListener('torStatus', (event) => {
setTorStatus(event?.detail);
});
}, []);
useEffect(() => {
setTheme(makeTheme(settings));
@ -46,9 +53,9 @@ const App = (): JSX.Element => {
{window.NativeRobosats === undefined ? (
<UnsafeAlert settings={settings} setSettings={setSettings} />
) : (
<TorConnection />
<TorConnectionBadge torStatus={torStatus} />
)}
<Main settings={settings} setSettings={setSettings} />
<Main settings={settings} setSettings={setSettings} torStatus={torStatus} />
</ThemeProvider>
</I18nextProvider>
</Suspense>

View File

@ -71,10 +71,11 @@ interface SlideDirection {
interface MainProps {
settings: Settings;
torStatus: 'NOTINIT' | 'STARTING' | '"Done"' | 'DONE';
setSettings: (state: Settings) => void;
}
const Main = ({ settings, setSettings }: MainProps): JSX.Element => {
const Main = ({ torStatus, settings, setSettings }: MainProps): JSX.Element => {
const { t } = useTranslation();
const theme = useTheme();
@ -351,6 +352,7 @@ const Main = ({ settings, setSettings }: MainProps): JSX.Element => {
<div>
<RobotPage
setPage={setPage}
torStatus={torStatus}
setCurrentOrder={setCurrentOrder}
windowSize={windowSize}
robot={robot}

View File

@ -131,7 +131,7 @@ const RobotProfile = ({
<Grid item>
<Button
disabled={robot.avatarLoaded && robot.nickname}
disabled={!(robot.avatarLoaded && robot.nickname)}
size='small'
color='primary'
onClick={() => {

View File

@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Paper, Grid, useTheme } from '@mui/material';
import { Paper, Grid, CircularProgress, Box, Alert, Typography, useTheme } from '@mui/material';
import { useParams } from 'react-router-dom';
import { Page } from '../NavBar';
@ -14,24 +14,25 @@ import Onboarding from './Onboarding';
import Welcome from './Welcome';
import RobotProfile from './RobotProfile';
import Recovery from './Recovery';
import { TorIcon } from '../../components/Icons';
interface RobotPageProps {
setPage: (state: Page) => void;
setCurrentOrder: (state: number) => void;
torStatus: 'NOTINIT' | 'STARTING' | '"Done"' | 'DONE';
robot: Robot;
setRobot: (state: Robot) => void;
windowSize: { width: number; height: number };
fetchRobot: ({}) => void;
baseUrl: string;
}
const RobotPage = ({
setPage,
setCurrentOrder,
torStatus,
windowSize,
robot,
setRobot,
fetchRobot,
baseUrl,
}: RobotPageProps): JSX.Element => {
const { t } = useTranslation();
@ -39,6 +40,7 @@ const RobotPage = ({
const refCode = params.refCode;
const width = Math.min(windowSize.width * 0.8, 28);
const maxHeight = windowSize.height * 0.85 - 3;
const theme = useTheme();
const [robotFound, setRobotFound] = useState<boolean>(false);
const [badRequest, setBadRequest] = useState<string | undefined>(undefined);
@ -141,70 +143,116 @@ const RobotPage = ({
systemClient.deleteItem('enc_priv_key');
};
return (
<Paper
elevation={12}
style={{
width: `${width}em`,
maxHeight: `${maxHeight}em`,
overflow: 'auto',
overflowX: 'clip',
}}
>
{/* TOR LOADING
Your connection is being encrypted and annonimized using the TOR Network. This ensures maximum privacy, however you might feel it is a bit slow. You could eventually lose connection from time to time, restart the app.
*/}
if (window?.NativeRobosats & (torStatus != 'DONE')) {
return (
<Paper
elevation={12}
style={{
width: `${width}em`,
maxHeight: `${maxHeight}em`,
}}
>
<Grid container direction='column' alignItems='center' spacing={1} padding={2}>
<Grid item>
<Typography align='center' variant='h5'>
{t('Connecting to TOR')}
</Typography>
</Grid>
<Grid item>
<Box>
<svg width={0} height={0}>
<linearGradient id='linearColors' x1={1} y1={0} x2={1} y2={1}>
<stop offset={0} stopColor={theme.palette.primary.main} />
<stop offset={1} stopColor={theme.palette.secondary.main} />
</linearGradient>
</svg>
<CircularProgress thickness={3} style={{ width: '11.2em', height: '11.2em' }} />
<Box sx={{ position: 'fixed', top: '4.6em' }}>
<TorIcon
sx={{
fill: 'url(#linearColors)',
width: '6em',
height: '6em',
position: 'relative',
left: '0.7em',
}}
/>
</Box>
</Box>
</Grid>
<Grid item>
<Alert>
<b>{t('Your traffic is encrypted and annonimized using TOR. ')}</b>
{t(
'This ensures maximum privacy, however you might feel the app behaves slow. If connection is lost, restart the app.',
)}
</Alert>
</Grid>
</Grid>
</Paper>
);
} else {
return (
<Paper
elevation={12}
style={{
width: `${width}em`,
maxHeight: `${maxHeight}em`,
overflow: 'auto',
overflowX: 'clip',
}}
>
{view === 'welcome' ? (
<Welcome setView={setView} getGenerateRobot={getGenerateRobot} width={width} />
) : null}
{view === 'welcome' ? (
<Welcome setView={setView} getGenerateRobot={getGenerateRobot} width={width} />
) : null}
{view === 'onboarding' ? (
<Onboarding
setView={setView}
robot={robot}
setRobot={setRobot}
badRequest={badRequest}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
{view === 'onboarding' ? (
<Onboarding
setView={setView}
robot={robot}
setRobot={setRobot}
badRequest={badRequest}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
{view === 'profile' ? (
<RobotProfile
setView={setView}
robot={robot}
robotFound={robotFound}
setRobot={setRobot}
badRequest={badRequest}
logoutRobot={logoutRobot}
width={width}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
{view === 'profile' ? (
<RobotProfile
setView={setView}
robot={robot}
robotFound={robotFound}
setRobot={setRobot}
badRequest={badRequest}
logoutRobot={logoutRobot}
width={width}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
{view === 'recovery' ? (
<Recovery
setView={setView}
robot={robot}
setRobot={setRobot}
badRequest={badRequest}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
</Paper>
);
{view === 'recovery' ? (
<Recovery
setView={setView}
robot={robot}
setRobot={setRobot}
badRequest={badRequest}
inputToken={inputToken}
setInputToken={setInputToken}
getGenerateRobot={getGenerateRobot}
setPage={setPage}
baseUrl={baseUrl}
/>
) : null}
</Paper>
);
}
};
export default RobotPage;

View File

@ -0,0 +1,395 @@
import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
import {
Button,
Tooltip,
Grid,
Typography,
TextField,
ButtonGroup,
CircularProgress,
IconButton,
} from '@mui/material';
import SmartToyIcon from '@mui/icons-material/SmartToy';
import CasinoIcon from '@mui/icons-material/Casino';
import ContentCopy from '@mui/icons-material/ContentCopy';
import BoltIcon from '@mui/icons-material/Bolt';
import DownloadIcon from '@mui/icons-material/Download';
import { RoboSatsNoTextIcon } from '../components/Icons';
import { sha256 } from 'js-sha256';
import { genBase62Token, tokenStrength, saveAsJson } from '../utils';
import { genKey } from '../pgp';
import { systemClient } from '../services/System';
import { apiClient } from '../services/api/index';
import RobotAvatar from '../components/RobotAvatar';
class UserGenPage extends Component {
constructor(props) {
super(props);
this.state = {
tokenHasChanged: false,
inputToken: '',
found: false,
};
this.refCode = this.props.match.params.refCode;
}
componentDidMount() {
// Checks in parent HomePage if there is already a nick and token
// Displays the existing one
if (this.props.robot.nickname != null) {
this.setState({ inputToken: this.props.robot.token });
} else if (this.props.robot.token) {
this.setState({ inputToken: this.props.robot.token });
this.getGeneratedUser(this.props.robot.token);
} else {
const newToken = genBase62Token(36);
this.setState({
inputToken: newToken,
});
this.getGeneratedUser(newToken);
}
}
getGeneratedUser = (token) => {
const strength = tokenStrength(token);
const refCode = this.refCode;
this.props.setRobot({ ...this.props.robot, loading: true, avatarLoaded: false });
const requestBody = genKey(token).then(function (key) {
return {
token_sha256: sha256(token),
public_key: key.publicKeyArmored,
encrypted_private_key: key.encryptedPrivateKeyArmored,
unique_values: strength.uniqueValues,
counts: strength.counts,
length: token.length,
ref_code: refCode,
};
});
requestBody.then((body) =>
apiClient.post(this.props.baseUrl, '/api/user/', body).then((data) => {
this.setState({ found: data.found, bad_request: data.bad_request });
this.props.setCurrentOrder(
data.active_order_id
? data.active_order_id
: data.last_order_id
? data.last_order_id
: null,
);
// Add nick and token to App state (token only if not a bad request)
data.bad_request
? this.props.setRobot({
...this.props.robot,
avatarLoaded: true,
loading: false,
nickname: data.nickname ?? this.props.robot.nickname,
activeOrderId: data.active_order_id ?? null,
referralCode: data.referral_code ?? this.props.referralCode,
earnedRewards: data.earned_rewards ?? this.props.earnedRewards,
lastOrderId: data.last_order_id ?? this.props.lastOrderId,
stealthInvoices: data.wants_stealth ?? this.props.stealthInvoices,
tgEnabled: data.tg_enabled,
tgBotName: data.tg_bot_name,
tgToken: data.tg_token,
})
: this.props.setRobot({
...this.props.robot,
nickname: data.nickname,
token,
loading: false,
activeOrderId: data.active_order_id ? data.active_order_id : null,
lastOrderId: data.last_order_id ? data.last_order_id : null,
referralCode: data.referral_code,
earnedRewards: data.earned_rewards ?? 0,
stealthInvoices: data.wants_stealth,
tgEnabled: data.tg_enabled,
tgBotName: data.tg_bot_name,
tgToken: data.tg_token,
bitsEntropy: data.token_bits_entropy,
shannonEntropy: data.token_shannon_entropy,
pubKey: data.public_key,
encPrivKey: data.encrypted_private_key,
copiedToken: data.found ? true : this.props.robot.copiedToken,
}) &
systemClient.setItem('robot_token', token) &
systemClient.setItem('pub_key', data.public_key.split('\n').join('\\')) &
systemClient.setItem('enc_priv_key', data.encrypted_private_key.split('\n').join('\\'));
}),
);
};
delGeneratedUser() {
apiClient.delete(this.props.baseUrl, '/api/user');
systemClient.deleteCookie('sessionid');
systemClient.deleteItem('robot_token');
systemClient.deleteItem('pub_key');
systemClient.deleteItem('enc_priv_key');
}
handleClickNewRandomToken = () => {
const inputToken = genBase62Token(36);
this.setState({
inputToken,
tokenHasChanged: true,
});
this.props.setRobot({ ...this.props.robot, copiedToken: true });
};
handleChangeToken = (e) => {
this.setState({
inputToken: e.target.value.split(' ').join(''),
tokenHasChanged: true,
});
};
handleClickSubmitToken = () => {
this.delGeneratedUser();
this.getGeneratedUser(this.state.inputToken);
this.setState({ tokenHasChanged: false });
this.props.setRobot({
...this.props.robot,
avatarLoaded: false,
nickname: null,
token: null,
copiedToken: false,
lastOrderId: null,
activeOrderId: null,
});
};
createJsonFile = () => {
return {
token: this.props.robot.token,
token_shannon_entropy: this.props.robot.shannonEntropy,
token_bit_entropy: this.props.robot.bitsEntropy,
public_key: this.props.robot.pub_key,
encrypted_private_key: this.props.robot.enc_priv_key,
};
};
render() {
const { t, i18n } = this.props;
const fontSize = this.props.theme.typography.fontSize;
const fontSizeFactor = fontSize / 14; // to scale sizes, default fontSize is 14
return (
<Grid container spacing={1}>
<Grid item>
<div className='clickTrough' />
</Grid>
<Grid
item
xs={12}
align='center'
sx={{ width: 370 * fontSizeFactor, height: 260 * fontSizeFactor }}
>
{this.props.robot.avatarLoaded && this.props.robot.nickname ? (
<div>
<Grid item xs={12} align='center'>
<Typography component='h5' variant='h5'>
<b>
{this.props.robot.nickname && systemClient.getCookie('sessionid') ? (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexWrap: 'wrap',
height: 45 * fontSizeFactor,
}}
>
<BoltIcon
sx={{
color: '#fcba03',
height: 33 * fontSizeFactor,
width: 33 * fontSizeFactor,
}}
/>
<a>{this.props.robot.nickname}</a>
<BoltIcon
sx={{
color: '#fcba03',
height: 33 * fontSizeFactor,
width: 33 * fontSizeFactor,
}}
/>
</div>
) : (
''
)}
</b>
</Typography>
</Grid>
<Grid item xs={12} align='center'>
<RobotAvatar
nickname={this.props.robot.nickname}
smooth={true}
style={{ maxWidth: 203 * fontSizeFactor, maxHeight: 203 * fontSizeFactor }}
imageStyle={{
transform: '',
border: '2px solid #555',
filter: 'drop-shadow(1px 1px 1px #000000)',
height: `${201 * fontSizeFactor}px`,
width: `${201 * fontSizeFactor}px`,
}}
tooltip={t('This is your trading avatar')}
tooltipPosition='top'
baseUrl={this.props.baseUrl}
/>
<br />
</Grid>
</div>
) : (
<CircularProgress sx={{ position: 'relative', top: 100 }} />
)}
</Grid>
{this.state.found ? (
<Grid item xs={12} align='center'>
<Typography variant='subtitle2' color='primary'>
{this.state.found ? t('A robot avatar was found, welcome back!') : null}
<br />
</Typography>
</Grid>
) : (
''
)}
<Grid container align='center'>
<Grid item xs={12} align='center'>
<TextField
sx={{ maxWidth: 280 * fontSizeFactor }}
error={!!this.state.bad_request}
label={t('Store your token safely')}
required={true}
value={this.state.inputToken}
variant='standard'
helperText={this.state.bad_request}
size='small'
onChange={this.handleChangeToken}
onKeyPress={(e) => {
if (e.key === 'Enter') {
this.handleClickSubmitToken();
}
}}
InputProps={{
startAdornment: (
<div
style={{
width: 50 * fontSizeFactor,
minWidth: 50 * fontSizeFactor,
position: 'relative',
left: -6,
}}
>
<Grid container>
<Grid item xs={6}>
<Tooltip
enterTouchDelay={250}
title={t('Save token and PGP credentials to file')}
>
<span>
<IconButton
color='primary'
disabled={
!this.props.robot.avatarLoaded ||
!(systemClient.getItem('robot_token') == this.state.inputToken)
}
onClick={() =>
saveAsJson(
this.props.robot.nickname + '.json',
this.createJsonFile(),
)
}
>
<DownloadIcon
sx={{ width: 22 * fontSizeFactor, height: 22 * fontSizeFactor }}
/>
</IconButton>
</span>
</Tooltip>
</Grid>
<Grid item xs={6}>
<Tooltip disableHoverListener enterTouchDelay={0} title={t('Copied!')}>
<IconButton
color={this.props.robot.copiedToken ? 'inherit' : 'primary'}
disabled={
!this.props.robot.avatarLoaded ||
!(systemClient.getItem('robot_token') === this.state.inputToken)
}
onClick={() =>
systemClient.copyToClipboard(systemClient.getItem('robot_token')) &
this.props.setRobot({ ...this.props.robot, copiedToken: true })
}
>
<ContentCopy
sx={{ width: 18 * fontSizeFactor, height: 18 * fontSizeFactor }}
/>
</IconButton>
</Tooltip>
</Grid>
</Grid>
</div>
),
endAdornment: (
<Tooltip enterTouchDelay={250} title={t('Generate a new token')}>
<IconButton onClick={this.handleClickNewRandomToken}>
<CasinoIcon
sx={{ width: 18 * fontSizeFactor, height: 18 * fontSizeFactor }}
/>
</IconButton>
</Tooltip>
),
}}
/>
</Grid>
</Grid>
<Grid item xs={12} align='center'>
{this.state.tokenHasChanged ? (
<Button type='submit' size='small' onClick={this.handleClickSubmitToken}>
<SmartToyIcon sx={{ width: 18 * fontSizeFactor, height: 18 * fontSizeFactor }} />
<span> {t('Generate Robot')}</span>
</Button>
) : (
<Tooltip
enterTouchDelay={0}
enterDelay={500}
enterNextDelay={2000}
title={t('You must enter a new token first')}
>
<div>
<Button disabled={true} type='submit' size='small'>
<SmartToyIcon sx={{ width: 18 * fontSizeFactor, height: 18 * fontSizeFactor }} />
<span>{t('Generate Robot')}</span>
</Button>
</div>
</Tooltip>
)}
</Grid>
<Grid item xs={12} align='center' sx={{ width: '26.43em' }}>
<Grid item>
<div style={{ height: '2.143em' }} />
</Grid>
<div style={{ width: '26.43em', left: '2.143em' }}>
<Grid container align='center'>
<Grid item xs={0.8} />
<Grid item xs={7.5} align='right'>
<Typography component='h5' variant='h5'>
{t('Simple and Private LN P2P Exchange')}
</Typography>
</Grid>
<Grid item xs={2.5} align='left'>
<RoboSatsNoTextIcon color='primary' sx={{ height: '3.143em', width: '3.143em' }} />
</Grid>
</Grid>
</div>
</Grid>
</Grid>
);
}
}
export default withTranslation()(UserGenPage);

View File

@ -2,16 +2,20 @@ import React, { useEffect, useState } from 'react';
import { Box, CircularProgress, Tooltip } from '@mui/material';
import { TorIcon } from './Icons';
import { useTranslation } from 'react-i18next';
import { gridQuickFilterValuesSelector } from '@mui/x-data-grid';
interface Props {
interface TorIndicatorProps {
color: 'inherit' | 'error' | 'warning' | 'success' | 'primary' | 'secondary' | 'info' | undefined;
tooltipOpen?: boolean | undefined;
title: string;
progress: boolean;
}
const TorIndicator = ({ color, tooltipOpen = undefined, title, progress }: Props): JSX.Element => {
const TorIndicator = ({
color,
tooltipOpen = undefined,
title,
progress,
}: TorIndicatorProps): JSX.Element => {
return (
<Tooltip
open={tooltipOpen}
@ -49,15 +53,12 @@ const TorIndicator = ({ color, tooltipOpen = undefined, title, progress }: Props
);
};
const TorConnection = (): JSX.Element => {
const [torStatus, setTorStatus] = useState<string>('NOTINIT');
const { t } = useTranslation();
interface TorConnectionBadgeProps {
torStatus: 'NOTINIT' | 'STARTING' | '"Done"' | 'DONE';
}
useEffect(() => {
window.addEventListener('torStatus', (event) => {
setTorStatus(event?.detail);
});
}, []);
const TorConnectionBadge = ({ torStatus }: TorConnectionBadgeProps): JSX.Element => {
const { t } = useTranslation();
if (window?.NativeRobosats == null) {
return <></>;
@ -95,4 +96,4 @@ const TorConnection = (): JSX.Element => {
}
};
export default TorConnection;
export default TorConnectionBadge;