summaryrefslogtreecommitdiffhomepage
path: root/gui/src/renderer/components/Connect.tsx
blob: dea950b3f141e6e2074454ff39c434d69229ddf2 (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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import * as React from 'react';
import { Component, Styles, View } from 'reactxp';
import { links } from '../../config.json';
import { ITunnelEndpoint, parseSocketAddress } from '../../shared/daemon-rpc-types';
import AccountExpiry from '../lib/account-expiry';
import { AuthFailureKind, parseAuthFailure } from '../lib/auth-failure';
import { IConnectionReduxState } from '../redux/connection/reducers';
import { IVersionReduxState } from '../redux/version/reducers';
import ExpiredAccountErrorView, { RecoveryAction } from './ExpiredAccountErrorView';
import { Brand, HeaderBarStyle, SettingsBarButton } from './HeaderBar';
import ImageView from './ImageView';
import { Container, Header, Layout } from './Layout';
import Map, { MarkerStyle, ZoomLevel } from './Map';
import NotificationArea from './NotificationArea';
import TunnelControl, { IRelayInAddress, IRelayOutAddress } from './TunnelControl';

interface IProps {
  connection: IConnectionReduxState;
  version: IVersionReduxState;
  accountExpiry?: AccountExpiry;
  selectedRelayName: string;
  connectionInfoOpen: boolean;
  blockWhenDisconnected: boolean;
  onSettings: () => void;
  onSelectLocation: () => void;
  onConnect: () => void;
  onDisconnect: () => void;
  onExternalLink: (url: string) => void;
  onToggleConnectionInfo: (value: boolean) => void;
}

type MarkerOrSpinner = 'marker' | 'spinner';

const styles = {
  connect: Styles.createViewStyle({
    flex: 1,
  }),
  map: Styles.createViewStyle({
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    // @ts-ignore
    zIndex: 0,
  }),
  body: Styles.createViewStyle({
    flex: 1,
    paddingTop: 0,
    paddingLeft: 24,
    paddingRight: 24,
    paddingBottom: 0,
    marginTop: 186,
  }),
  container: Styles.createViewStyle({
    flex: 1,
    flexDirection: 'column',
    position: 'relative' /* need this for z-index to work to cover the map */,
    // @ts-ignore
    zIndex: 1,
  }),
  statusIcon: Styles.createViewStyle({
    position: 'absolute',
    alignSelf: 'center',
    width: 60,
    height: 60,
    marginTop: 94,
  }),
  notificationArea: Styles.createViewStyle({
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
  }),
};

interface IState {
  isAccountExpired: boolean;
}

export default class Connect extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);

    this.state = {
      isAccountExpired: this.checkAccountExpired(props, false),
    };
  }

  public componentDidUpdate() {
    this.updateAccountExpired();
  }

  public render() {
    return (
      <Layout>
        <Header barStyle={this.headerBarStyle()}>
          <Brand />
          <SettingsBarButton onPress={this.props.onSettings} />
        </Header>
        <Container>
          {this.state.isAccountExpired ? this.renderExpiredAccountView() : this.renderMap()}
        </Container>
      </Layout>
    );
  }

  private updateAccountExpired() {
    const nextAccountExpired = this.checkAccountExpired(this.props, this.state.isAccountExpired);

    if (nextAccountExpired !== this.state.isAccountExpired) {
      this.setState({
        isAccountExpired: nextAccountExpired,
      });
    }
  }

  private checkAccountExpired(props: IProps, prevAccountExpired: boolean): boolean {
    const tunnelState = props.connection.status;

    // Blocked with auth failure / expired account
    if (
      tunnelState.state === 'blocked' &&
      tunnelState.details.reason === 'auth_failed' &&
      parseAuthFailure(tunnelState.details.details).kind === AuthFailureKind.expiredAccount
    ) {
      return true;
    }

    // Use the account expiry to deduce the account state
    if (this.props.accountExpiry) {
      return this.props.accountExpiry.hasExpired();
    }

    // Do not assume that the account hasn't expired if the expiry is not available at the moment
    // instead return the last known state.
    return prevAccountExpired;
  }

  private renderExpiredAccountView() {
    return (
      <ExpiredAccountErrorView
        blockWhenDisconnected={this.props.blockWhenDisconnected}
        isBlocked={this.props.connection.isBlocked}
        action={this.handleExpiredAccountRecovery}
      />
    );
  }

  private renderMap() {
    const status = this.props.connection.status;

    const relayOutAddress: IRelayOutAddress = {
      ipv4: this.props.connection.ipv4,
      ipv6: this.props.connection.ipv6,
    };
    const relayInAddress: IRelayInAddress | undefined =
      (status.state === 'connecting' || status.state === 'connected') && status.details
        ? this.tunnelEndpointToRelayInAddress(status.details)
        : undefined;

    return (
      <View style={styles.connect}>
        <Map style={styles.map} {...this.getMapProps()} />
        <View style={styles.container}>
          {/* show spinner when connecting */}
          {this.showMarkerOrSpinner() === 'spinner' ? (
            <View style={styles.statusIcon}>
              <ImageView source="icon-spinner" height={60} width={60} />
            </View>
          ) : null}

          <TunnelControl
            tunnelState={this.props.connection.status}
            selectedRelayName={this.props.selectedRelayName}
            city={this.props.connection.city}
            country={this.props.connection.country}
            hostname={this.props.connection.hostname}
            defaultConnectionInfoOpen={this.props.connectionInfoOpen}
            relayInAddress={relayInAddress}
            relayOutAddress={relayOutAddress}
            onConnect={this.props.onConnect}
            onDisconnect={this.props.onDisconnect}
            onSelectLocation={this.props.onSelectLocation}
            onToggleConnectionInfo={this.props.onToggleConnectionInfo}
          />

          <NotificationArea
            style={styles.notificationArea}
            tunnelState={this.props.connection.status}
            version={this.props.version}
            accountExpiry={this.props.accountExpiry}
            openExternalLink={this.props.onExternalLink}
            blockWhenDisconnected={this.props.blockWhenDisconnected}
          />
        </View>
      </View>
    );
  }

  private handleExpiredAccountRecovery = async (recoveryAction: RecoveryAction) => {
    switch (recoveryAction) {
      case RecoveryAction.disableBlockedWhenDisconnected:
        break;

      case RecoveryAction.openBrowser:
        this.props.onExternalLink(links.purchase);
        break;

      case RecoveryAction.disconnectAndOpenBrowser:
        try {
          await this.props.onDisconnect();
          this.props.onExternalLink(links.purchase);
        } catch (error) {
          // no-op
        }
    }
  };

  private headerBarStyle(): HeaderBarStyle {
    const { status } = this.props.connection;
    switch (status.state) {
      case 'disconnected':
        return HeaderBarStyle.error;
      case 'connecting':
      case 'connected':
        return HeaderBarStyle.success;
      case 'blocked':
        switch (status.details.reason) {
          case 'set_firewall_policy_error':
            return HeaderBarStyle.error;
          default:
            return HeaderBarStyle.success;
        }
      case 'disconnecting':
        switch (status.details) {
          case 'block':
          case 'reconnect':
            return HeaderBarStyle.success;
          case 'nothing':
            return HeaderBarStyle.error;
          default:
            throw new Error(`Invalid action after disconnection: ${status.details}`);
        }
    }
  }

  private getMapProps(): Map['props'] {
    const {
      longitude,
      latitude,
      status: { state },
    } = this.props.connection;

    // when the user location is known
    if (typeof longitude === 'number' && typeof latitude === 'number') {
      return {
        center: [longitude, latitude],
        // do not show the marker when connecting or reconnecting
        showMarker: this.showMarkerOrSpinner() === 'marker',
        markerStyle: this.getMarkerStyle(),
        // zoom in when connected
        zoomLevel: state === 'connected' ? ZoomLevel.low : ZoomLevel.medium,
        // a magic offset to align marker with spinner
        offset: [0, 123],
      };
    } else {
      return {
        center: [0, 0],
        showMarker: false,
        markerStyle: MarkerStyle.unsecure,
        // show the world when user location is not known
        zoomLevel: ZoomLevel.high,
        // remove the offset since the marker is hidden
        offset: [0, 0],
      };
    }
  }

  private getMarkerStyle(): MarkerStyle {
    const { status } = this.props.connection;

    switch (status.state) {
      case 'connecting':
      case 'connected':
        return MarkerStyle.secure;
      case 'blocked':
        switch (status.details.reason) {
          case 'set_firewall_policy_error':
            return MarkerStyle.unsecure;
          default:
            return MarkerStyle.secure;
        }
      case 'disconnected':
        return MarkerStyle.unsecure;
      case 'disconnecting':
        switch (status.details) {
          case 'block':
          case 'reconnect':
            return MarkerStyle.secure;
          case 'nothing':
            return MarkerStyle.unsecure;
          default:
            throw new Error(`Invalid action after disconnection: ${status.details}`);
        }
    }
  }

  private showMarkerOrSpinner(): MarkerOrSpinner {
    const status = this.props.connection.status;

    return status.state === 'connecting' ||
      (status.state === 'disconnecting' && status.details === 'reconnect')
      ? 'spinner'
      : 'marker';
  }

  private tunnelEndpointToRelayInAddress(tunnelEndpoint: ITunnelEndpoint): IRelayInAddress {
    const socketAddr = parseSocketAddress(tunnelEndpoint.address);
    return {
      ip: socketAddr.host,
      port: socketAddr.port,
      protocol: tunnelEndpoint.protocol,
    };
  }
}