File size: 7,742 Bytes
7aec436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class CloudManager {
  constructor (parent) {
    this.parent = parent;
    this.providers = [];
    this.overrides = new Map();
  }

  hasCloudData () {
    return this.parent.vm.runtime.hasCloudData();
  }

  projectReady () {
    if (this.hasCloudData()) {
      for (const provider of this.providers) {
        provider.enable();
      }
    }
  }

  setVariable (provider, name, value) {
    if (this.overrides.has(name) && this.overrides.get(name) !== provider) {
      return;
    }
    this.parent.vm.postIOData('cloud', {
      varUpdate: {
        name,
        value
      }
    });
  }

  getUsername () {
    return this.parent._username;
  }

  addProvider (provider) {
    provider.manager = this;
    if (this.hasCloudData()) {
      provider.enable();
    }
    this.providers.push(provider);
  }

  requestCloseConnection () {
    // no-op
  }

  createVariable (name, value) {
    // no-op
  }

  renameVariable (oldName, newName) {
    // no-op
  }

  deleteVariable (name) {
    // no-op
  }

  addProviderOverride (name, provider) {
    if (provider && !this.providers.includes(provider)) {
      throw new Error('Manager is not aware of this provider');
    }
    this.overrides.set(name, provider);
  }

  updateVariable (name, value) {
    if (this.overrides.has(name)) {
      const provider = this.overrides.get(name);
      if (provider) {
        provider.handleUpdateVariable(name, value);
      }
      return;
    }
    for (const provider of this.providers) {
      provider.handleUpdateVariable(name, value);
    }
  }
}

class WebSocketProvider {
  /**

   * @param {string[]|string} cloudHost URLs of servers to connect to. Must start with ws: or wss:

   * If cloudHost is an array, the server will consecutively try each server until one connects.

   * @param {string} projectId The ID of the project

   */
  constructor(cloudHost, projectId) {
    this.cloudHosts = Array.isArray(cloudHost) ? cloudHost : [cloudHost];
    this.projectId = projectId;
    this.attemptedConnections = 0;
    this.bufferedMessages = [];
    this.scheduledBufferedSend = null;
    this.reconnectTimeout = null;
    this.openConnection = this.openConnection.bind(this);
    this._scheduledSendBufferedMessages = this._scheduledSendBufferedMessages.bind(this);
  }

  enable () {
    this.openConnection();
  }

  setProjectId (id) {
    this.projectId = id;
    this.closeAndReconnect();
  }

  openConnection () {
    this.currentCloudHost = this.cloudHosts[this.attemptedConnections % this.cloudHosts.length];
    this.attemptedConnections++;
    console.log(`Connecting to ${this.currentCloudHost} with ID ${this.projectId}, username ${this.manager.getUsername()}`);
    try {
      // Don't try to validate the cloud host ourselves. Let the browser do it.
      // Edge cases like ws://localhost being considered secure are too complex to handle correctly.
      this.ws = new WebSocket(this.currentCloudHost);
    } catch (e) {
      console.error(e);
      // The error message from the browser (especially Firefox) is sometimes very generic and not helpful.
      throw new Error(`Cloud host ${this.currentCloudHost} is invalid: ${e}`);
    }
    this.ws.onerror = this.onerror.bind(this);
    this.ws.onmessage = this.onmessage.bind(this);
    this.ws.onopen = this.onopen.bind(this);
    this.ws.onclose = this.onclose.bind(this);
  }

  onerror (event) {
    console.error('WebSocket error', event);
  }

  onmessage (event) {
    for (const line of event.data.split('\n')) {
      if (line) {
        const parsed = JSON.parse(line);
        if (parsed.method === 'set') {
          this.manager.setVariable(this, parsed.name, parsed.value);
        }
      }
    }
  }

  onopen () {
    this.attemptedConnections = 0;
    this.writeToServer({
      method: 'handshake'
    });
    this.sendBufferedMessages();
    console.log('WebSocket connected');
  }

  onclose (e) {
    // https://github.com/TurboWarp/cloud-server/blob/master/doc/protocol.md#status-codes
    if (e && e.code === 4002) {
      console.log('Username is invalid; not reconnecting.');
      return;
    }
    if (e && e.code === 4003) {
      console.log('Cloud variable server is full; not reconnecting.');
      return;
    }
    if (e && e.code === 4004) {
      console.log('Project is blocked; not reconnecting.');
      return;
    }
    const timeout = Math.random() * (Math.pow(2, Math.min(this.attemptedConnections + 1, 5)) - 1) * 1000;
    console.log(`Connection lost; reconnecting in ${Math.round(timeout)}ms`);
    this.reconnectTimeout = setTimeout(this.openConnection, timeout);
  }

  closeAndReconnect () {
    console.log('Closing connection and reconnecting.');
    if (this.ws) {
      this.ws.onclose = null;
      this.ws.onerror = null;
      this.ws.close();
    }
    clearTimeout(this.reconnectTimeout);
    // There should be a slight delay so that repeated project ID changes won't trigger too many connections.
    const delay = 1000 / 30;
    this.reconnectTimeout = setTimeout(this.openConnection, delay);
  }

  canWriteToServer () {
    return this.ws && this.ws.readyState === WebSocket.OPEN;
  }

  scheduleBufferedSend () {
    if (!this.scheduledBufferedSend) {
      this.scheduledBufferedSend = true;
      Promise.resolve().then(this._scheduledSendBufferedMessages);
    }
  }

  _scheduledSendBufferedMessages () {
    this.scheduledBufferedSend = false;
    if (this.canWriteToServer()) {
      this.sendBufferedMessages();
    }
  }

  sendBufferedMessages () {
    for (const message of this.bufferedMessages) {
      this.writeToServer(message);
    }
    this.bufferedMessages.length = 0;
  }

  bufferedWriteToServer (message) {
    this.bufferedMessages.push(message);
    this.scheduleBufferedSend();
  }

  writeToServer (message) {
    message.project_id = this.projectId;
    message.user = this.manager.getUsername();
    this.ws.send(JSON.stringify(message));
  }

  handleUpdateVariable (name, value) {
    // If this variable already has an update queued, we'll replace its value instead of adding another update.
    for (const i of this.bufferedMessages) {
      if (i.name === name) {
        i.value = value;
        return;
      }
    }
    this.bufferedWriteToServer({
      method: 'set',
      name,
      value
    });
  }
}

class LocalStorageProvider {
  constructor (key='p4:cloudvariables') {
    this.key = key;
    this.variables = {};
    this.handleStorageEvent = this.handleStorageEvent.bind(this);
  }

  readFromLocalStorage () {
    let parsed;
    try {
      parsed = JSON.parse(localStorage.getItem(this.key));
      if (!parsed || typeof parsed !== 'object') {
        return;
      }
    } catch (e) {
      return;
    }
    this.variables = parsed;
    for (const key of Object.keys(this.variables)) {
      this.manager.setVariable(this, key, this.variables[key]);
    }
  }

  storeToLocalStorage () {
    try {
      localStorage.setItem(this.key, JSON.stringify(this.variables))
    } catch (e) {
      // ignore
    }
  }

  handleStorageEvent (e) {
    if (e.key === this.key && e.storageArea === localStorage) {
      this.readFromLocalStorage();
    }
  }

  enable () {
    this.readFromLocalStorage();
    window.addEventListener('storage', this.handleStorageEvent);
  }

  handleUpdateVariable (name, value) {
    this.variables[name] = value;
    this.storeToLocalStorage();
  }
}

export default {
  CloudManager,
  WebSocketProvider,
  LocalStorageProvider
};