summaryrefslogtreecommitdiffhomepage
path: root/gui/src/renderer/components/Connect.tsx
blob: 58e7b4e7ba9108fbd1e501359ac74d04e8578d3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { useCallback, useMemo } from 'react';
import { sprintf } from 'sprintf-js';
import styled from 'styled-components';

import { ICustomList } from '../../shared/daemon-rpc-types';
import { messages, relayLocations } from '../../shared/gettext';
import log from '../../shared/logging';
import { useAppContext } from '../context';
import { transitions, useHistory } from '../lib/history';
import { RoutePath } from '../lib/routes';
import { IRelayLocationCountryRedux, RelaySettingsRedux } from '../redux/settings/reducers';
import { useSelector } from '../redux/store';
import { calculateHeaderBarStyle, DefaultHeaderBar } from './HeaderBar';
import ImageView from './ImageView';
import { Container, Layout } from './Layout';
import Map, { MarkerStyle, ZoomLevel } from './Map';
import NotificationArea from './NotificationArea';
import TunnelControl from './TunnelControl';

type MarkerOrSpinner = 'marker' | 'spinner' | 'none';

const StyledContainer = styled(Container)({
  position: 'relative',
});

const StyledMap = styled(Map)({
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  zIndex: 0,
});

const Content = styled.div({
  display: 'flex',
  flex: 1,
  flexDirection: 'column',
  position: 'relative', // need this for z-index to work to cover the map
  zIndex: 1,
});

const StatusIcon = styled(ImageView)({
  position: 'absolute',
  alignSelf: 'center',
  marginTop: 94,
});

const StyledNotificationArea = styled(NotificationArea)({
  position: 'absolute',
  left: 0,
  top: 0,
  right: 0,
});

const StyledMain = styled.main({
  display: 'flex',
  flexDirection: 'column',
  flex: 1,
});

export default function Connect() {
  const history = useHistory();
  const { connectTunnel, disconnectTunnel, reconnectTunnel } = useAppContext();

  const connection = useSelector((state) => state.connection);
  const blockWhenDisconnected = useSelector((state) => state.settings.blockWhenDisconnected);
  const relaySettings = useSelector((state) => state.settings.relaySettings);
  const relayLocations = useSelector((state) => state.settings.relayLocations);
  const customLists = useSelector((state) => state.settings.customLists);

  const mapCenter = useMemo<[number, number] | undefined>(() => {
    const { longitude, latitude } = connection;
    return typeof longitude === 'number' && typeof latitude === 'number'
      ? [longitude, latitude]
      : undefined;
  }, [connection]);

  const showMarkerOrSpinner = useMemo<MarkerOrSpinner>(() => {
    if (!mapCenter) {
      return 'none';
    }

    switch (connection.status.state) {
      case 'error':
        return 'none';
      case 'connecting':
      case 'disconnecting':
        return 'spinner';
      case 'connected':
      case 'disconnected':
        return 'marker';
    }
  }, [mapCenter, connection.status.state]);

  const markerStyle = useMemo<MarkerStyle>(() => {
    switch (connection.status.state) {
      case 'connecting':
      case 'connected':
        return MarkerStyle.secure;
      case 'error':
        return !connection.status.details.blockingError ? MarkerStyle.secure : MarkerStyle.unsecure;
      case 'disconnected':
        return MarkerStyle.unsecure;
      case 'disconnecting':
        switch (connection.status.details) {
          case 'block':
          case 'reconnect':
            return MarkerStyle.secure;
          case 'nothing':
            return MarkerStyle.unsecure;
        }
    }
  }, [connection.status]);

  const zoomLevel = useMemo<ZoomLevel>(() => {
    const { longitude, latitude } = connection;

    if (typeof longitude === 'number' && typeof latitude === 'number') {
      return connection.status.state === 'connected' ? ZoomLevel.high : ZoomLevel.medium;
    } else {
      return ZoomLevel.low;
    }
  }, [connection.latitude, connection.longitude, connection.status.state]);

  const mapProps = useMemo<Map['props']>(() => {
    return {
      center: mapCenter ?? [0, 0],
      showMarker: showMarkerOrSpinner === 'marker',
      markerStyle,
      zoomLevel,
      // a magic offset to align marker with spinner
      offset: [0, mapCenter ? 123 : 0],
    };
  }, [mapCenter, showMarkerOrSpinner, markerStyle, zoomLevel]);

  const onSelectLocation = useCallback(() => {
    history.push(RoutePath.selectLocation, { transition: transitions.show });
  }, [history.push]);

  const selectedRelayName = useMemo(
    () => getRelayName(relaySettings, customLists, relayLocations),
    [relaySettings, customLists, relayLocations],
  );

  const onConnect = useCallback(async () => {
    try {
      await connectTunnel();
    } catch (e) {
      const error = e as Error;
      log.error(`Failed to connect the tunnel: ${error.message}`);
    }
  }, []);

  const onDisconnect = useCallback(async () => {
    try {
      await disconnectTunnel();
    } catch (e) {
      const error = e as Error;
      log.error(`Failed to disconnect the tunnel: ${error.message}`);
    }
  }, []);

  const onReconnect = useCallback(async () => {
    try {
      await reconnectTunnel();
    } catch (e) {
      const error = e as Error;
      log.error(`Failed to reconnect the tunnel: ${error.message}`);
    }
  }, []);

  return (
    <Layout>
      <DefaultHeaderBar barStyle={calculateHeaderBarStyle(connection.status)} />
      <StyledContainer>
        <StyledMap {...mapProps} />
        <Content>
          <StyledNotificationArea />

          <StyledMain>
            {/* show spinner when connecting */}
            {showMarkerOrSpinner === 'spinner' ? (
              <StatusIcon source="icon-spinner" height={60} width={60} />
            ) : null}

            <TunnelControl
              tunnelState={connection.status}
              blockWhenDisconnected={blockWhenDisconnected}
              selectedRelayName={selectedRelayName}
              city={connection.city}
              country={connection.country}
              onConnect={onConnect}
              onDisconnect={onDisconnect}
              onReconnect={onReconnect}
              onSelectLocation={onSelectLocation}
            />
          </StyledMain>
        </Content>
      </StyledContainer>
    </Layout>
  );
}

function getRelayName(
  relaySettings: RelaySettingsRedux,
  customLists: Array<ICustomList>,
  locations: IRelayLocationCountryRedux[],
): string {
  if ('normal' in relaySettings) {
    const location = relaySettings.normal.location;

    if (location === 'any') {
      return 'Automatic';
    } else if ('customList' in location) {
      return customLists.find((list) => list.id === location.customList)?.name ?? 'Unknown';
    } else if ('hostname' in location) {
      const country = locations.find(({ code }) => code === location.country);
      if (country) {
        const city = country.cities.find(({ code }) => code === location.city);
        if (city) {
          return sprintf(
            // TRANSLATORS: The selected location label displayed on the main view, when a user selected a specific host to connect to.
            // TRANSLATORS: Example: Malmö (se-mma-001)
            // TRANSLATORS: Available placeholders:
            // TRANSLATORS: %(city)s - a city name
            // TRANSLATORS: %(hostname)s - a hostname
            messages.pgettext('connect-container', '%(city)s (%(hostname)s)'),
            {
              city: relayLocations.gettext(city.name),
              hostname: location.hostname,
            },
          );
        }
      }
    } else if ('city' in location) {
      const country = locations.find(({ code }) => code === location.country);
      if (country) {
        const city = country.cities.find(({ code }) => code === location.city);
        if (city) {
          return relayLocations.gettext(city.name);
        }
      }
    } else if ('country' in location) {
      const country = locations.find(({ code }) => code === location.country);
      if (country) {
        return relayLocations.gettext(country.name);
      }
    }

    return 'Unknown';
  } else if (relaySettings.customTunnelEndpoint) {
    return 'Custom';
  } else {
    throw new Error('Unsupported relay settings.');
  }
}