This repository has been archived by the owner on Oct 31, 2021. It is now read-only.
/
Socket.ts
278 lines (231 loc) 路 9.4 KB
/
Socket.ts
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
/* eslint-disable no-console */
import {DialogBox} from '@overlays/DialogBox';
import {UploadStream} from '@state/models/UploadStream';
import {prettyRemainingTime} from '@utils/pretty-remaining-time';
import {uid} from '@utils/uid';
import GracefulWebSocket from 'graceful-ws';
import {action, observable} from 'mobx';
import prettyBytes from 'pretty-bytes';
import {Upload} from '../models/Upload';
import {FileRefreshments, FileRegistrations, files} from './Files';
import {pushNotification} from './Notify';
import {resetRemoteSettings, settings, syncRemoteSettings} from './Settings';
import {uploads} from './Uploads';
export type ConnectionState = 'connected' | 'disconnected';
type RequestResolver = [
(resolve: unknown) => void,
(reason: unknown) => void
];
class Socket {
@observable public connectionState: ConnectionState;
private readonly requests: Map<string, RequestResolver>;
private readonly ws: GracefulWebSocket;
private connectionLost = false;
private messageQueue: Array<unknown>;
private sessionKey: string | null;
constructor() {
this.ws = new GracefulWebSocket(env.WS_ENDPOINT);
this.connectionState = 'disconnected';
this.messageQueue = [];
this.requests = new Map();
this.sessionKey = null;
this.ws.addEventListener('connected', () => {
console.log('[WS] Connected!');
if (settings.notifications.onConnectionChange && this.connectionLost) {
this.connectionLost = false;
// Show notification if enabled
pushNotification({
title: 'Connected again 馃構',
body: 'Share something!'
});
}
// Try to re-establish connection or create a new session
if (this.sessionKey !== null) {
console.log('[WS] Try to restore session.');
this.sendMessage('restore-session', this.sessionKey);
} else {
console.log('[WS] Request new session.');
this.sendMessage('create-session');
}
});
this.ws.addEventListener('disconnected', () => {
this.updateState('disconnected');
this.connectionLost = true;
console.log('[WS] Disconnected!');
// Show notification if enabled
if (settings.notifications.onConnectionChange) {
pushNotification({
title: 'Connection lost... 馃槩',
body: 'Tell your friends to wait a second, we\'re working on it!'
});
}
// Pause all uploads and mark all files as pending
uploads.massAction('pause');
files.resetFiles();
});
this.ws.addEventListener('message', (e: unknown) => {
try {
const {type, payload} = JSON.parse((e as MessageEvent).data);
this.onMessage(type, payload);
} catch (e) {
console.error(e);
}
});
}
get connected() {
return this.ws.connected;
}
public sendMessage(type: string, payload: unknown = null): void {
const message = {type, payload};
if (this.connected) {
this.ws.send(JSON.stringify(message));
} else {
this.messageQueue.push(message);
}
}
public request(type: string, data: unknown = null): Promise<unknown> {
return new Promise<unknown>((resolve, reject) => {
const id = uid('wsr');
this.sendMessage('request', {
id, type, data
});
this.requests.set(id, [resolve, reject]);
});
}
@action
private flushMessageQueue() {
// TODO: Bulk often empty!
if (!this.connected) {
throw new Error('Cannot clear message queue if not connected.');
}
this.ws.send(JSON.stringify({
type: 'bulk',
payload: this.messageQueue
}));
this.messageQueue = [];
}
@action
private updateState(newState: ConnectionState) {
this.connectionState = newState;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
private onMessage(type: string, payload: any): void {
switch (type) {
case 'response': {
const {id, ok, data} = payload;
const resolvers = this.requests.get(id);
if (!resolvers) {
console.warn(`[WS] Unknown response for id ${id}`);
break;
}
if (ok) {
resolvers[0](data);
} else {
resolvers[1](data);
}
break;
}
case 'restore-session': {
console.log('[WS] Session restored.');
// Restore settings and files
resetRemoteSettings(payload.settings);
files.activate(payload.files);
// Send pending messages
this.flushMessageQueue();
// Update state and session-key
this.updateState('connected');
this.sessionKey = payload.key;
break;
}
case 'new-session': {
console.log('[WS] New session started.');
// We're now "officially" connected
this.updateState('connected');
this.sessionKey = payload;
// Sync server-side settings, refresh keys and cancel uploads
syncRemoteSettings();
files.requestReRegistration();
uploads.performMassStatusUpdate('connection-lost', ...uploads.listedUploads);
this.flushMessageQueue();
break;
}
case 'register-files': {
files.activate(payload as FileRegistrations);
break;
}
case 'refresh-files': {
files.reActivate(payload as FileRefreshments);
break;
}
case 'file-request': {
const {fileId, downloadId} = payload;
const item = files.listedFiles.find(
value => value.id === fileId
);
if (!item) {
console.warn('[WS] File not longer available...');
break;
}
const upload = new Upload({
listedFile: item,
id: downloadId,
url: `${env.HTTPS_ENDPOINT}/b/file/${downloadId}`
});
uploads.registerUpload(upload);
break;
}
case 'stream-request': {
const {fileId, streamId, streamKey, range} = payload;
const item = files.listedFiles.find(
value => value.id === fileId
);
if (!item) {
console.warn('[WS] File not longer available...');
break;
}
const stream = uploads.listedUploads.find(value => {
return value instanceof UploadStream && value.streamKey === streamKey;
});
if (stream && range !== undefined) {
(stream as UploadStream).consume(range, `${env.HTTPS_ENDPOINT}/b/stream/${streamId}`, streamId);
} else {
const upload = new UploadStream(streamKey, item);
upload.consume(range, `${env.HTTPS_ENDPOINT}/b/stream/${streamId}`, streamId);
uploads.registerUpload(upload);
}
break;
}
case 'stream-cancelled': {
uploads.cancelStream(payload);
break;
}
case 'download-cancelled': {
const target = uploads.listedUploads.find(v => v.id === payload);
if (target) {
uploads.performMassStatusUpdate('peer-cancelled', target);
}
break;
}
case 'rate-limited': {
console.log('[WS] Rate limited.', payload);
const description =
'Rate limits are used to prevent abuse. ' +
`It's currently set to ${prettyBytes(payload.limit)} and you've exceeded that limit, pending downloads have been cancelled. ` +
`Wait ${prettyRemainingTime(payload.remainingTime)} until you can upload something again.`;
void DialogBox.instance.open({
icon: 'low-connection',
title: 'You\'ve been rate limited!',
description,
buttons: [
{text: 'Okay'}
]
});
break;
}
default: {
console.warn(`[WS] Unknown action: ${type}`);
}
}
}
}
export const socket = new Socket();