/
websockets.js
77 lines (63 loc) · 2.1 KB
/
websockets.js
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
import { Emitter } from '@rocket.chat/emitter';
import { Meteor } from 'meteor/meteor';
import { CachedCollectionManager } from '../../../../app/ui-cached-collection/client';
import { loadButtons } from '../../../../app/ui-message/client/ActionButtonSyncer';
import { APIClient, slashCommands } from '../../../../app/utils/client';
export const AppEvents = Object.freeze({
APP_ADDED: 'app/added',
APP_REMOVED: 'app/removed',
APP_UPDATED: 'app/updated',
APP_STATUS_CHANGE: 'app/statusUpdate',
APP_SETTING_UPDATED: 'app/settingUpdated',
COMMAND_ADDED: 'command/added',
COMMAND_DISABLED: 'command/disabled',
COMMAND_UPDATED: 'command/updated',
COMMAND_REMOVED: 'command/removed',
ACTIONS_CHANGED: 'actions/changed',
});
export class AppWebsocketReceiver extends Emitter {
constructor() {
super();
this.streamer = new Meteor.Streamer('apps');
CachedCollectionManager.onLogin(() => {
this.listenStreamerEvents();
});
}
listenStreamerEvents() {
Object.values(AppEvents).forEach((eventName) => {
this.streamer.on(eventName, this.emit.bind(this, eventName));
});
this.streamer.on(AppEvents.COMMAND_ADDED, this.onCommandAddedOrUpdated);
this.streamer.on(AppEvents.COMMAND_UPDATED, this.onCommandAddedOrUpdated);
this.streamer.on(AppEvents.COMMAND_REMOVED, this.onCommandRemovedOrDisabled);
this.streamer.on(AppEvents.COMMAND_DISABLED, this.onCommandRemovedOrDisabled);
this.streamer.on(AppEvents.ACTIONS_CHANGED, this.onActionsChanged);
}
registerListener(event, listener) {
this.on(event, listener);
}
unregisterListener(event, listener) {
this.off(event, listener);
}
onCommandAddedOrUpdated = (command) => {
const retryOnFailure = (retries) => {
APIClient.get('/v1/commands.get', { command })
.then((result) => {
slashCommands.add(result.command);
})
.catch((error) => {
if (retries - 1 === 0) {
throw error;
}
setTimeout(() => {
retryOnFailure(retries - 1);
}, 3000);
});
};
retryOnFailure(3);
};
onCommandRemovedOrDisabled = (command) => {
delete slashCommands.commands[command];
};
onActionsChanged = () => loadButtons();
}