summaryrefslogtreecommitdiffhomepage
path: root/app/lib/backend.js
blob: 0add43f24f49ffcdd6d9af76542ef849803ff497 (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
import Enum from './enum';
import { EventEmitter } from 'events';

const EventType = Enum('connect', 'connecting', 'disconnect', 'login', 'logging', 'logout', 'updatedIp');

/**
 * Backend implementation
 * 
 * @class Backend
 */
export default class Backend extends EventEmitter {
  
  static EventType = EventType;
  
  constructor() {
    super();
    this._account = null;
    this._loggedIn = false;
    this._serverAddress = null;
    this._cancellationHandler = null;

    // update IP in background
    setTimeout(::this.refreshIp, 0);
  }

  // Accessors

  get account() { return this._account; }
  get loggedIn() { return this._loggedIn; }
  get serverAddress() { return this._serverAddress; }

  // Public methods

  login(account) {
    this._account = account;

    // emit: logging in
    this.emit(EventType.logging, account);

    // @TODO: Add login call
    setTimeout(() => {
      let err;
      if(!account.startsWith('1111')) {
        err = new Error('Invalid account number.');
      }
      // emit: login
      this.emit(EventType.login, account, err);
    }, 2000);
  }

  logout() {
    this._account = null;

    // emit event
    this.emit(EventType.logout);

    // @TODO: Add logout call
  }

  connect(addr) {
    this._serverAddress = addr;

    // emit: connecting
    this.emit(EventType.connecting, addr);
    
    // @TODO: Add connect call
    let timer = null;

    timer = setTimeout(() => {
      let err;
      // if(!/se\d+\.mullvad\.net/.test(addr)) {
      //   err = new Error('Server is unreachable');
      // }
      // emit: connect
      this.emit(EventType.connect, addr, err);
      this.refreshIp();

      // reset timer
      timer = null;
      this._cancellationHandler  = null;
    }, 5000);

    this._cancellationHandler = () => {
      if(timer !== null) {
        clearTimeout(timer);
        this._timer = null;
      }
      this._cancellationHandler = null;
    };
  }

  disconnect() {
    this._serverAddress = null;

    // cancel ongoing connection attempt
    if(this._cancellationHandler) {
      this._cancellationHandler();
    } else {
      this.refreshIp();
    }

    // emit: disconnect
    this.emit(EventType.disconnect);

    // @TODO: Add disconnect call
  }

  refreshIp() {
    let ip = [];
    for(let i = 0; i < 4; i++) {
      ip.push(parseInt(Math.random() * 253 + 1));
    }
    this.emit(EventType.updatedIp, ip.join('.'));
  }
}