aboutsummaryrefslogtreecommitdiff
path: root/src/server/websocket.ts
blob: f10455680330eb03e4b68aa09b4c6884fcb3538f (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import { blue } from 'colors';
import { createServer } from 'https';
import * as _ from 'lodash';
import { networkInterfaces } from 'os';
import { Server, Socket } from 'socket.io';
import { SecureContextOptions } from 'tls';
import { ServerUtils } from '../ServerUtils';
import { serializedDoctype, serializedFieldsType } from '../fields/ObjectField';
import { logPort } from './ActionUtilities';
import { Client } from './Client';
import { DashStats } from './DashStats';
import { DocumentsCollection } from './IDatabase';
import { Diff, GestureContent, MessageStore } from './Message';
import { resolvedPorts, socketMap, timeMap, userOperations } from './SocketData';
import { initializeGuest } from './authentication/DashUserModel';
import { Database } from './database';

// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace WebSocket {
    let CurUser: string | undefined;
    export let _socket: Socket;
    export let _disconnect: () => void;
    export const clients: { [key: string]: Client } = {};

    function processGesturePoints(socket: Socket, content: GestureContent) {
        socket.broadcast.emit('receiveGesturePoints', content);
    }

    export async function doDelete(onlyFields = true) {
        const target: string[] = [];
        onlyFields && target.push(DocumentsCollection);
        await Database.Instance.dropSchema(...target);
        initializeGuest();
    }

    function printActiveUsers() {
        socketMap.forEach((user, socket) => !socket.disconnected && console.log(user));
    }
    function barReceived(socket: Socket, userEmail: string) {
        clients[userEmail] = new Client(userEmail.toString());
        const currentdate = new Date();
        const datetime = currentdate.getDate() + '/' + (currentdate.getMonth() + 1) + '/' + currentdate.getFullYear() + ' @ ' + currentdate.getHours() + ':' + currentdate.getMinutes() + ':' + currentdate.getSeconds();
        console.log(blue(`user ${userEmail} has connected to the web socket at: ${datetime}`));
        printActiveUsers();

        timeMap[userEmail] = Date.now();
        socketMap.set(socket, userEmail + ' at ' + datetime);
        userOperations.set(userEmail, 0);
        DashStats.logUserLogin(userEmail);
    }

    function GetRefFieldLocal([id, callback]: [string, (result?: serializedDoctype) => void]) {
        return Database.Instance.getDocument(id, callback);
    }
    function GetRefField([id, callback]: [string, (result?: serializedDoctype) => void]) {
        process.stdout.write(`+`);
        GetRefFieldLocal([id, callback]);
    }

    function GetRefFields([ids, callback]: [string[], (result?: serializedDoctype[]) => void]) {
        process.stdout.write(`${ids.length}…`);
        Database.Instance.getDocuments(ids, callback);
    }

    const suffixMap: { [type: string]: string | [string, string | ((json: any) => any)] } = {
        number: '_n',
        string: '_t',
        boolean: '_b',
        image: ['_t', 'url'],
        video: ['_t', 'url'],
        pdf: ['_t', 'url'],
        audio: ['_t', 'url'],
        web: ['_t', 'url'],
        map: ['_t', 'url'],
        script: ['_t', value => value.script.originalScript],
        RichTextField: ['_t', value => value.Text],
        date: ['_d', value => new Date(value.date).toISOString()],
        proxy: ['_i', 'fieldId'],
        list: [
            '_l',
            list => {
                const results: any[] = [];
                // eslint-disable-next-line no-use-before-define
                list.fields.forEach((value: any) => ToSearchTerm(value) && results.push(ToSearchTerm(value)!.value));
                return results.length ? results : null;
            },
        ],
    };

    function ToSearchTerm(valIn: any): { suffix: string; value: any } | undefined {
        let val = valIn;
        if (val === null || val === undefined) {
            return undefined;
        }
        const type = val.__type || typeof val;

        let suffix = suffixMap[type];
        if (!suffix) {
            return undefined;
        }
        if (Array.isArray(suffix)) {
            const accessor = suffix[1];
            if (typeof accessor === 'function') {
                val = accessor(val);
            } else {
                val = val[accessor];
            }
            [suffix] = suffix;
        }
        return { suffix, value: val };
    }

    function getSuffix(value: string | [string, any]): string {
        return typeof value === 'string' ? value : value[0];
    }
    const pendingOps = new Map<string, { diff: Diff; socket: Socket }[]>();

    function dispatchNextOp(id: string) {
        const next = pendingOps.get(id)!.shift();
        if (next) {
            const { diff, socket } = next;
            if (diff.diff.$addToSet) {
                // eslint-disable-next-line no-use-before-define
                return GetRefFieldLocal([diff.id, (result?: serializedDoctype) => addToListField(socket, diff, result)]); // would prefer to have Mongo handle list additions direclty, but for now handle it on our own
            }
            if (diff.diff.$remFromSet) {
                // eslint-disable-next-line no-use-before-define
                return GetRefFieldLocal([diff.id, (result?: serializedDoctype) => remFromListField(socket, diff, result)]); // would prefer to have Mongo handle list additions direclty, but for now handle it on our own
            }
            // eslint-disable-next-line no-use-before-define
            return SetField(socket, diff);
        }
        return !pendingOps.get(id)!.length && pendingOps.delete(id);
    }

    function addToListField(socket: Socket, diffIn: Diff, listDoc?: serializedDoctype): void {
        const diff = diffIn;
        diff.diff.$set = diff.diff.$addToSet;
        delete diff.diff.$addToSet; // convert add to set to a query of the current fields, and then a set of the composition of the new fields with the old ones
        const updatefield = Array.from(Object.keys(diff.diff.$set ?? {}))[0];
        const newListItems = diff.diff.$set?.[updatefield]?.fields;
        if (!newListItems) {
            console.log('Error: addToListField - no new list items');
            return;
        }
        const listItems = listDoc?.fields?.[updatefield.replace('fields.', '')]?.fields.filter(item => item !== undefined) ?? [];
        if (diff.diff.$set?.[updatefield]?.fields !== undefined) {
            diff.diff.$set[updatefield]!.fields = [...listItems, ...newListItems]; // , ...newListItems.filter((newItem: any) => newItem === null || !curList.some((curItem: any) => curItem.fieldId ? curItem.fieldId === newItem.fieldId : curItem.heading ? curItem.heading === newItem.heading : curItem === newItem))];
            const sendBack = diff.diff.length !== diff.diff.$set[updatefield]!.fields?.length;
            delete diff.diff.length;
            Database.Instance.update(
                diff.id,
                diff.diff,
                () => {
                    if (sendBack) {
                        console.log('Warning: list modified during update. Composite list is being returned.');
                        const { id } = socket;
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        (socket as any).id = ''; // bcz: HACK to reference private variable.  this allows the update message to go back to the client that made the change.
                        socket.broadcast.emit(MessageStore.UpdateField.Message, diff);
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        (socket as any).id = id;
                    } else {
                        socket.broadcast.emit(MessageStore.UpdateField.Message, diff);
                    }
                    dispatchNextOp(diff.id);
                },
                false
            );
        }
    }

    /**
     * findClosestIndex() is a helper function that will try to find
     * the closest index of a list that has the same value as
     * a specified argument/index pair.
     * @param list the list to search through
     * @param indexesToDelete a list of indexes that are already marked for deletion
     * so they will be ignored
     * @param value the value of the item to remove
     * @param hintIndex the index that the element was at on the client's copy of
     * the data
     * @returns the closest index with the same value or -1 if the element was not found.
     */
    function findClosestIndex(list: { fieldId: string; __type: string }[], indexesToDelete: number[], value: { fieldId: string; __type: string }, hintIndex: number) {
        let closestIndex = -1;
        for (let i = 0; i < list.length; i++) {
            if (list[i] === value && !indexesToDelete.includes(i)) {
                if (Math.abs(i - hintIndex) < Math.abs(closestIndex - hintIndex)) {
                    closestIndex = i;
                }
            }
        }
        return closestIndex;
    }

    /**
     * remFromListField() receives the items to remove and a hint
     * from the client, and attempts to make the modification to the
     * server's copy of the data. If server's copy does not match
     * the client's after removal, the server will SEND BACk
     * its version to the client.
     * @param socket the socket that the client is connected on
     * @param diff an object containing the items to remove and a hint
     * (the hint contains start index and deleteCount, the number of
     * items to delete)
     * @param curListItems the server's current copy of the data
     */
    function remFromListField(socket: Socket, diffIn: Diff, curListItems?: serializedDoctype): void {
        const diff = diffIn;
        diff.diff.$set = diff.diff.$remFromSet as serializedFieldsType;
        const hint = diff.diff.$remFromSet?.hint;
        delete diff.diff.$remFromSet;
        const updatefield = Array.from(Object.keys(diff.diff.$set ?? {}))[0];
        const remListItems = diff.diff.$set[updatefield]?.fields;
        if (diff.diff.$set[updatefield] !== undefined && remListItems) {
            const curList = curListItems?.fields?.[updatefield.replace('fields.', '')]?.fields.filter(f => f !== null) || [];

            if (hint) {
                // indexesToRemove stores the indexes that we mark for deletion, which is later used to filter the list (delete the elements)
                const indexesToRemove: number[] = [];
                for (let i = 0; i < hint.deleteCount; i++) {
                    if (curList.length > i + hint.start && _.isEqual(curList[i + hint.start], remListItems[i])) {
                        indexesToRemove.push(i + hint.start);
                    } else {
                        const closestIndex = findClosestIndex(curList, indexesToRemove, remListItems[i], i + hint.start);
                        if (closestIndex !== -1) {
                            indexesToRemove.push(closestIndex);
                        } else {
                            console.log('Item to delete was not found - index = -1');
                        }
                    }
                }
                diff.diff.$set[updatefield]!.fields = curList.filter((curItem, index) => !indexesToRemove.includes(index));
            } else {
                // go back to the original way to delete if we didn't receive
                // a hint from the client
                diff.diff.$set[updatefield]!.fields = curList?.filter(curItem => !remListItems.some(remItem => (remItem.fieldId ? remItem.fieldId === curItem.fieldId : remItem.heading ? remItem.heading === curItem.heading : remItem === curItem)));
            }
            // if the client and server have different versions of the data after
            // deletion, they will have different lengths and the server will
            // send its version of the data to the client
            const sendBack = diff.diff.length !== remListItems.length;
            delete diff.diff.length;
            Database.Instance.update(
                diff.id,
                diff.diff,
                () => {
                    if (sendBack) {
                        // the two copies are different, so the server sends its copy.
                        console.log('SEND BACK');
                        const { id } = socket;
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        (socket as any).id = ''; // bcz: HACK to access private variable  this allows the update message to go back to the client that made the change.
                        socket.broadcast.emit(MessageStore.UpdateField.Message, diff);
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        (socket as any).id = id;
                    } else {
                        socket.broadcast.emit(MessageStore.UpdateField.Message, diff);
                    }
                    dispatchNextOp(diff.id);
                },
                false
            );
        }
    }

    function UpdateField(socket: Socket, diff: Diff) {
        const curUser = socketMap.get(socket);
        if (!curUser) return false;
        const currentUsername = curUser.split(' ')[0];
        userOperations.set(currentUsername, userOperations.get(currentUsername) !== undefined ? userOperations.get(currentUsername)! + 1 : 0);

        if (CurUser !== socketMap.get(socket)) {
            CurUser = socketMap.get(socket);
            console.log('Switch User: ' + CurUser);
        }
        if (pendingOps.has(diff.id)) {
            pendingOps.get(diff.id)!.push({ diff, socket });
            return true;
        }
        pendingOps.set(diff.id, [{ diff, socket }]);
        if (diff.diff.$addToSet) {
            return GetRefFieldLocal([diff.id, (result?: serializedDoctype) => addToListField(socket, diff, result)]); // would prefer to have Mongo handle list additions direclty, but for now handle it on our own
        }
        if (diff.diff.$remFromSet) {
            return GetRefFieldLocal([diff.id, (result?: serializedDoctype) => remFromListField(socket, diff, result)]); // would prefer to have Mongo handle list additions direclty, but for now handle it on our own
        }
        // eslint-disable-next-line no-use-before-define
        return SetField(socket, diff);
    }
    function SetField(socket: Socket, diff: Diff /* , curListItems?: Transferable */) {
        Database.Instance.update(diff.id, diff.diff, () => socket.broadcast.emit(MessageStore.UpdateField.Message, diff), false);
        dispatchNextOp(diff.id);
    }

    function DeleteField(socket: Socket, id: string) {
        Database.Instance.delete({ _id: id }).then(() => {
            socket.broadcast.emit(MessageStore.DeleteField.Message, id);
        });
    }

    function DeleteFields(socket: Socket, ids: string[]) {
        Database.Instance.delete({ _id: { $in: ids } }).then(() => {
            socket.broadcast.emit(MessageStore.DeleteFields.Message, ids);
        });
    }

    export async function initialize(isRelease: boolean, credentials: SecureContextOptions) {
        let io: Server;
        if (isRelease) {
            const { socketPort } = process.env;
            if (socketPort) {
                resolvedPorts.socket = Number(socketPort);
            }
            const httpsServer = createServer(credentials);
            io = new Server(httpsServer, {});
            httpsServer.listen(resolvedPorts.socket);
        } else {
            io = new Server();
            io.listen(resolvedPorts.socket);
        }
        logPort('websocket', resolvedPorts.socket);

        io.on('connection', socket => {
            _socket = socket;
            socket.use((_packet, next) => {
                const userEmail = socketMap.get(socket);
                if (userEmail) {
                    timeMap[userEmail] = Date.now();
                }
                next();
            });

            socket.emit(MessageStore.UpdateStats.Message, DashStats.getUpdatedStatsBundle());

            socket.on('message', (message, room) => {
                console.log('Client said: ', message);
                socket.in(room).emit('message', message);
            });

            socket.on('ipaddr', () => {
                networkInterfaces().keys?.forEach(dev => {
                    if (dev.family === 'IPv4' && dev.address !== '127.0.0.1') {
                        socket.emit('ipaddr', dev.address);
                    }
                });
            });

            socket.on('bye', () => {
                console.log('received bye');
            });

            socket.on('disconnect', () => {
                const currentUser = socketMap.get(socket);
                if (!(currentUser === undefined)) {
                    const currentUsername = currentUser.split(' ')[0];
                    DashStats.logUserLogout(currentUsername);
                    delete timeMap[currentUsername];
                }
            });

            ServerUtils.Emit(socket, MessageStore.Foo, 'handshooken');

            ServerUtils.AddServerHandler(socket, MessageStore.Bar, guid => barReceived(socket, guid));
            if (isRelease) {
                ServerUtils.AddServerHandler(socket, MessageStore.DeleteAll, () => doDelete(false));
            }

            ServerUtils.AddServerHandler(socket, MessageStore.UpdateField, diff => UpdateField(socket, diff));
            ServerUtils.AddServerHandler(socket, MessageStore.DeleteField, id => DeleteField(socket, id));
            ServerUtils.AddServerHandler(socket, MessageStore.DeleteFields, ids => DeleteFields(socket, ids));
            ServerUtils.AddServerHandler(socket, MessageStore.GesturePoints, content => processGesturePoints(socket, content));
            ServerUtils.AddServerHandlerCallback(socket, MessageStore.GetRefField, GetRefField);
            ServerUtils.AddServerHandlerCallback(socket, MessageStore.GetRefFields, GetRefFields);

            /**
             * Whenever we receive the go-ahead, invoke the import script and pass in
             * as an emitter and a terminator the functions that simply broadcast a result
             * or indicate termination to the client via the web socket
             */

            _disconnect = () => {
                socket.broadcast.emit('connection_terminated', Date.now());
                socket.disconnect(true);
            };
        });

        setInterval(() => {
            // Utils.Emit(socket, MessageStore.UpdateStats, DashStats.getUpdatedStatsBundle());

            io.emit(MessageStore.UpdateStats.Message, DashStats.getUpdatedStatsBundle());
        }, DashStats.SAMPLING_INTERVAL);
    }
}