-
Notifications
You must be signed in to change notification settings - Fork 29
/
slackpost.js
1389 lines (1257 loc) · 39.2 KB
/
slackpost.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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TODO: create channels transparently when sending to `@` channels?
* TODO: disable the `interval` to refreshState() since we should have all
* RTM listeners in place now?
*
* https://nodered.org/blog/2019/09/20/node-done
*/
module.exports = function (RED) {
"use strict";
const { RTMClient } = require("@slack/rtm-api");
const { WebClient } = require("@slack/web-api");
/**
* https://nodered.org/docs/creating-nodes/status
* The shape property can be: ring or dot
* The fill property can be: red, green, yellow, blue or grey
*/
var statuses = {
connecting: { fill: "yellow", shape: "ring", text: "connecting" },
connected: { fill: "green", shape: "dot", text: "connected" },
disconnected: { fill: "red", shape: "ring", text: "disconnected" },
misconfigured: { fill: "red", shape: "ring", text: "misconfigured" },
error: { fill: "red", shape: "dot", text: "error" },
sending: { fill: "blue", shape: "dot", text: "sending" },
blank: {},
};
function SlackDebug() {
var debug = process.env.SLACK_DEBUG ? true : false;
if (!debug) {
return;
}
// 16-5-2015 9:50:11
var d = new Date();
var datestring =
d.getFullYear() +
"-" +
(d.getMonth() + 1) +
"-" +
d.getDate() +
" " +
d.getHours() +
":" +
d.getMinutes() +
":" +
d.getSeconds();
var prefix = datestring + " - [debug] ";
console.log(
"---------------------------------------------------------------------"
);
console.log(prefix + "slack");
if (arguments.length > 1) {
arguments[0] = arguments[0] + "\n";
}
console.log(...arguments);
console.log(
"---------------------------------------------------------------------"
);
}
/**
* turn any value into a string
* https://webbjocke.com/javascript-check-data-types/
*
* @param {*} value
*/
function ValueToString(value) {
if (value && typeof value === "object" && value.constructor === Array) {
return JSON.stringify(value);
}
if (value && typeof value === "object" && value.constructor === Object) {
return JSON.stringify(value);
}
/**
* seeing some really weird cases where the above fail but "" + value
* returns '[object Object]'
*/
if (value && typeof value === "object") {
return JSON.stringify(value);
}
if (value === null || typeof value === "undefined") {
return "";
}
if (typeof value === "boolean") {
if (value) {
return "true";
} else {
return "false";
}
}
if (typeof value === "number" && isFinite(value)) {
return value.toString();
}
if (!!(value && value.constructor && value.call && value.apply)) {
return value.toString();
}
return "" + value;
}
/**
* Common event listeners to set status indicators
*
* @param {*} node
*/
function SetConfigNodeConnectionListeners(node) {
node.clientNode.rtmClient.on("connecting", () => {
node.status(statuses.connecting);
});
node.clientNode.rtmClient.on("ready", () => {
node.status(statuses.connected);
});
node.clientNode.rtmClient.on("disconnected", (e) => {
var status = statuses.disconnected;
/**
* {
* code: 'slackclient_platform_error',
* data: { ok: false, error: 'invalid_auth' }
* }
*/
if (e.code == "slackclient_platform_error" && e.data.ok === false) {
status.text = e.data.error;
}
node.status(status);
});
/**
* if connectivity is dropped we go from connected -> reconnecting
* directly bypassing disconnected
*/
node.clientNode.rtmClient.on("reconnecting", () => {
node.status(statuses.disconnected);
});
}
/**
* Slack client helper to recursively request a resource using pagination
* https://slack.dev/node-slack-sdk/web_api#pagination
*
* @param {*} client
* @param {*} method
* @param {*} property
* @param {*} options
*/
function RecursivePaginatedWebCall(client, method, property, options = {}) {
/**
* store all entries
*/
var data = [];
/**
* count of recursive calls required
*/
var rcount = 0;
return new Promise((resolve, reject) => {
function recurse() {
rcount++;
client
.apiCall(method, options)
.then((res) => {
data = data.concat(res[property]);
/**
* if more pages, keep going otherwise resolve the promise
*/
if (
res.response_metadata &&
res.response_metadata.next_cursor &&
res.response_metadata.next_cursor !== ""
) {
options.cursor = res.response_metadata.next_cursor;
// keep recursing
recurse();
} else {
resolve(data);
}
})
.catch((e) => {
reject(e);
});
}
// start recursion
recurse();
});
}
/**
* Connection/configuration NODE for slack api
* make note that when the flows are deployed this function will be
* re-ran (along with other nodes)
*
* @param {*} n
*/
function SlackConfig(n) {
RED.nodes.createNode(this, n);
var node = this;
this.options = {};
this.state = {};
this.webClient = null;
this.rtmClient = null;
this.shortToken = function () {
if (this.credentials && this.credentials.hasOwnProperty("token")) {
var token = this.credentials.token;
return token.substr(0, 8) + "..." + token.substr(token.length - 3);
}
};
if (this.credentials && this.credentials.hasOwnProperty("token")) {
/**
* This can be used to pre-emptively valid API calls when check against
* this scopes the user has
*
* https://api.slack.com/docs/token-types
*/
var tokenType = null;
if (this.credentials.token.startsWith("xoxp-")) {
tokenType = "user";
} else if (this.credentials.token.startsWith("xoxb-")) {
tokenType = "bot";
} else {
// TODO: validate this on the config node
tokenType = "invalid";
}
/**
* meta method to refresh all state data
*/
this.refreshState = function () {
SlackDebug("refreshing state " + this.shortToken());
var promises = [];
promises.push(this.refreshTeam());
promises.push(this.refreshChannels());
promises.push(this.refreshMembers());
promises.push(this.refreshBots());
promises.push(this.refreshUser());
promises.push(this.refreshDnd());
return Promise.all(promises)
.then(() => {
this.emit("state_refreshed", {});
})
.catch((e) => {
this.error(e);
});
};
/**
* update local cache of channels
*/
this.refreshChannels = function () {
/**
* TODO: ensure this does not happen too frequent
* get all channels
* https://api.slack.com/methods/conversations.list
*/
return RecursivePaginatedWebCall(
this.webClient,
"conversations.list",
"channels",
{
limit: 1000,
exclude_archived: true,
types: "public_channel,private_channel,im,mpim",
}
)
.then((res) => {
var channels = {};
res.forEach((item) => {
channels[item.id] = item;
});
this.state.channels = channels;
})
.catch((e) => {
this.error(e);
});
};
/**
* update local cache of members
*/
this.refreshMembers = function () {
/**
* TODO: ensure this does not happen too frequent
* get all members
* https://api.slack.com/methods/users.list
*/
return RecursivePaginatedWebCall(
this.webClient,
"users.list",
"members",
{
limit: 1000,
}
)
.then((res) => {
this.state.presence = this.state.presence || {};
var members = {};
res.forEach((item) => {
members[item.id] = item;
});
this.state.members = members;
})
.catch((e) => {
this.error(e);
});
};
/**
* update local cache of bots
*/
this.refreshBots = function () {
var promises = [];
this.state.bots = this.state.bots || {};
for (var id in this.state.bots) {
if (this.state.bots.hasOwnProperty(id)) {
SlackDebug("webrequest to find bot: " + id);
var p = this.webClient
.apiCall("bots.info", { bot: id })
.then((res) => {
this.state.bots[id] = res.bot;
})
.catch((e) => {
this.error(e);
});
promises.push(p);
}
}
return Promise.all(promises)
.then(() => {
// TODO: update any internal flags?
})
.catch((e) => {
this.error(e);
});
};
/**
* update local cache of team
*/
this.refreshTeam = function () {
/**
* TODO: ensure this does not happen too frequent
* https://api.slack.com/methods/team.info
*/
return this.webClient
.apiCall("team.info")
.then((res) => {
this.state.team = res.team;
})
.catch((e) => {
this.error(e);
});
};
/**
* update local cache of identity
*/
this.refreshUser = function () {
/**
* TODO: ensure this does not happen too frequent
* https://api.slack.com/methods/users.identity
*/
if (this.state.connection.self.id) {
return this.webClient
.apiCall("users.identity", { user: this.state.connection.self.id })
.then((res) => {
this.state.user = res.user;
})
.catch((e) => {
//this.error(e);
});
}
};
/**
* update local cache of dnd
*/
this.refreshDnd = function () {
return this.webClient
.apiCall("dnd.teamInfo")
.then((res) => {
this.state.dnd = res.users;
})
.catch((e) => {
//this.error(e);
});
};
/**
* lookup member based off of id
*/
this.findMemberById = function (id) {
SlackDebug("looking up member: " + id);
this.state.members = this.state.members || {};
return this.state.members[id];
};
/**
* lookup member based off of name or @name syntax
*/
this.findMemberByName = function (name) {
SlackDebug("looking up member: " + name);
this.state.members = this.state.members || {};
for (var id in this.state.members) {
if (this.state.members.hasOwnProperty(id)) {
if (
this.state.members[id].deleted === false &&
this.state.members[id].name == name.replace(/^@/, "")
) {
return this.state.members[id];
}
}
}
};
/**
* lookup channel based off of id
*/
this.findChannelById = function (id) {
SlackDebug("looking up channel: " + id);
this.state.channels = this.state.channels || {};
return this.state.channels[id];
};
/**
* channels start with:
* C - Conference (normal rooms)
* G - Group (multiuser, and private channels)
* D - Direct (user to user)
*/
this.findChannelByName = function (name, type = null) {
SlackDebug("looking up channel: " + name);
this.state.channels = this.state.channels || {};
/**
* this purposely does a lookup on both regardless to handle
* use-cases where the # or @ is ommitted completely
*/
var directChannel = null;
var roomChannel = null;
// do lockup by member name
var member = this.findMemberByName(name);
if (member) {
for (var id in this.state.channels) {
if (this.state.channels.hasOwnProperty(id)) {
if (
this.state.channels[id].id[0] == "D" &&
this.state.channels[id].is_user_deleted === false &&
this.state.channels[id].user == member.id
) {
directChannel = this.state.channels[id];
break;
}
}
}
}
// do lookup by channel name
for (var id in this.state.channels) {
if (this.state.channels.hasOwnProperty(id)) {
if (
this.state.channels[id].is_archived === false &&
this.state.channels[id].name == name.replace(/^#/, "")
) {
roomChannel = this.state.channels[id];
break;
}
}
}
if (name[0] == "@") {
return directChannel;
} else if (name[0] == "#") {
return roomChannel;
} else {
return directChannel || roomChannel;
}
};
/**
* lookup bot based off of id
*/
this.findBotById = function (id) {
SlackDebug("looking up bot: " + id);
this.state.bots = this.state.bots || {};
var bot = this.state.bots[id];
if (!bot) {
SlackDebug("webrequest to find bot: " + id);
this.webClient
.apiCall("bots.info", { bot: id })
.then((res) => {
this.state.bots[id] = res.bot;
})
.catch((e) => {
//ignore
});
}
return bot;
};
/**
* Takes raw responses from RTM/Web API and adds additional properties
* to help looking up names/etc as msg flows through nodered
*/
this.dressResponseMessage = function (res) {
var node = this;
var depth = 0;
function recurse(data) {
depth++;
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key];
/**
* prevent infinite recursion by only going 2 deep
*/
if (typeof value === "object" && depth < 2) {
recurse(value);
continue;
}
/**
* dress users, channels, teams, etc
*/
if (key.includes("user")) {
if (typeof value === "string" || value instanceof String) {
if (!data.hasOwnProperty(key + "Object")) {
var member = node.findMemberById(value);
if (member) {
data[key + "Object"] = member;
}
}
}
} else if (key.includes("channel")) {
if (typeof value === "string" || value instanceof String) {
if (!data.hasOwnProperty(key + "Object")) {
var channel = node.findChannelById(value);
if (channel) {
data[key + "Object"] = channel;
}
}
}
} else if (key.includes("team")) {
if (typeof value === "string" || value instanceof String) {
if (!data.hasOwnProperty(key + "Object")) {
if (value == node.state.team.id)
data[key + "Object"] = node.state.team;
}
}
} else if (key.includes("bot")) {
if (typeof value === "string" || value instanceof String) {
if (!data.hasOwnProperty(key + "Object")) {
var bot = node.findBotById(value);
if (bot) {
data[key + "Object"] = bot;
}
}
}
}
}
}
--depth;
}
try {
recurse(res);
} catch (e) {
node.error(e);
}
return res;
};
/**
* https://api.slack.com/methods
* https://slack.dev/node-slack-sdk/web_api
* https://github.com/slackapi/node-slack-sdk/blob/master/src/WebClient.ts
*/
this.webClient = new WebClient(this.credentials.token);
/**
* https://slack.dev/node-slack-sdk/rtm_api
* https://slack.dev/node-slack-sdk/rtm_api#lifecycle-events
* https://api.slack.com/rtm#events
* https://github.com/slackapi/node-slack-sdk/blob/master/src/RTMClient.ts
*
* by default autoReconnect=true and keepAlive settings are enabled
*/
this.rtmClient = new RTMClient(this.credentials.token, {
logLevel: process.env.SLACK_DEBUG ? "debug" : "info",
retryConfig: {
forever: true,
minTimeout: 1 * 1000,
maxTimeout: 5 * 1000,
},
});
this.rtmClient.on("disconnected", (e) => {
SlackDebug("disconnected " + this.shortToken(), e);
this.log(
RED._("node-red:common.status.disconnected") +
" from slack with token: " +
this.shortToken()
);
clearInterval(this.refreshIntervalId);
});
this.rtmClient.on("connecting", () => {
SlackDebug("connecting " + this.shortToken());
clearInterval(this.refreshIntervalId);
});
this.rtmClient.on("authenticated", () => {
SlackDebug("authenticated " + this.shortToken());
});
this.rtmClient.on("connected", () => {
SlackDebug("connected " + this.shortToken());
this.log(
RED._("node-red:common.status.connected") +
" to slack with token: " +
this.shortToken()
);
// what is worse, no data or potentially stale data?
this.state.presence = {};
this.refreshState()
.then(() => {
this.emit("state_initialized", {});
})
.catch((e) => {
this.error(e);
});
// TODO: make this a node configurable item
var interval = 10 * 60 * 1000;
this.refreshIntervalId = setInterval(function () {
node.refreshState();
}, interval);
this.on("close", () => {
clearInterval(this.refreshIntervalId);
});
});
this.rtmClient.on("ready", () => {
SlackDebug("ready " + this.shortToken());
});
this.rtmClient.on("disconnecting", () => {
SlackDebug("disconnecting " + this.shortToken());
clearInterval(this.refreshIntervalId);
});
/**
* if connectivity is dropped we go from connected -> reconnecting
* directly bypassing disconnected
*/
this.rtmClient.on("reconnecting", () => {
SlackDebug("reconnecting " + this.shortToken());
this.log(
RED._("node-red:common.status.disconnected") +
" from slack with token: " +
this.shortToken()
);
clearInterval(this.refreshIntervalId);
});
this.rtmClient.on("error", (e) => {
SlackDebug("error " + this.shortToken(), e);
});
this.rtmClient.on("unable_to_rtm_start", (e) => {
SlackDebug("unable_to_rtm_start " + this.shortToken(), e);
});
/**
* This is meant to keep state current
* - bots
* - members
* - channels
* - team
* - dnd
* - presence (only listen to what the user has subscribed to manually)
*/
this.rtmClient.on("slack_event", (eventType, event) => {
switch (eventType) {
case "user_change":
case "team_join":
this.state.members = this.state.members || {};
this.state.members[event.user.id] = event.user;
break;
case "bot_added":
case "bot_changed":
this.state.bots = this.state.bots || {};
this.state.bots[event.bot.id] = event.bot;
break;
case "channel_deleted":
case "group_deleted":
this.state.channels = this.state.channels || {};
delete this.state.channels[event.channel];
break;
case "channel_created":
case "channel_joined":
case "channel_rename":
case "group_joined":
case "group_rename":
case "im_created":
this.webClient
.apiCall("channels.info", { channel: event.channel.id })
.then((res) => {
this.state.channels = this.state.channels || {};
this.state.channels[res.channel.id] = res.channel;
})
.catch((e) => {
console.log("failed getting channel info", e);
});
break;
case "channel_archive":
case "channel_left":
case "channel_unarchive":
case "group_archive":
case "group_close":
case "group_left":
case "group_open":
case "group_unarchive":
case "im_close":
case "im_open":
case "member_joined_channel":
case "member_left_channel":
this.webClient
.apiCall("channels.info", { channel: event.channel })
.then((res) => {
this.state.channels = this.state.channels || {};
this.state.channels[res.channel.id] = res.channel;
})
.catch((e) => {
console.log("failed getting channel info", e);
});
break;
case "presence_change":
this.state.presence = this.state.presence || {};
if (event.user) {
var res = {
type: event.type,
presence: event.presence,
user: event.user,
};
this.state.presence[event.user] = res;
}
if (event.users) {
event.users.forEach((user) => {
var res = {
type: event.type,
presence: event.presence,
user: user,
};
this.state.presence[user] = res;
});
}
break;
case "manual_presence_change":
this.state.presence = this.state.presence || {};
this.this.state.presence[this.state.connection.self.id] = {
type: event.type,
presence: event.presence,
user: this.state.connection.self.id,
};
break;
case "dnd_updated":
case "dnd_updated_user":
this.state.dnd = this.state.dnd || {};
this.state.dnd[event.user] = event.dnd_status;
break;
case "team_rename":
case "team_domain_change":
case "team_plan_change":
case "team_pref_change":
case "team_profile_change":
case "team_profile_delete":
case "team_profile_reorder":
this.webClient
.apiCall("team.info")
.then((res) => {
this.state.team = res.team;
})
.catch((e) => {
console.log("failed getting team info", e);
});
break;
default:
// do nothing
break;
}
});
this.startClient = function () {
/**
* may consider using the .connect() method instead
* https://api.slack.com/methods/rtm.start
* https://api.slack.com/methods/rtm.connect
*/
this.rtmClient
.start()
.then((res) => {
SlackDebug("start result " + this.shortToken(), res);
this.state.connection = {};
this.state.connection.self = res.self;
this.state.connection.url = res.url;
this.state.connection.scopes = res.scopes;
this.state.connection.acceptedScopes = res.acceptedScopes;
})
.catch((e) => {
console.log("failed starting slack session", e);
});
};
this.startClient();
//start watchdog
this.connectionWatchdog = function () {
//var interval = (5 * 60 * 1000);
var interval = 15 * 1000;
var lastState = null;
var stateAt = null;
var maxUnconnectedStateSeconds = 30;
var intervalId = setInterval(() => {
SlackDebug("watchdog connection details", {
connected: this.rtmClient.connected,
currentState: this.rtmClient.stateMachine.getCurrentState(),
currentStateAt: stateAt,
});
if (lastState === null) {
lastState = this.rtmClient.stateMachine.getCurrentState();
stateAt = Date.now();
}
if (
!this.rtmClient.connected &&
lastState == this.rtmClient.stateMachine.getCurrentState() &&
(Date.now() - stateAt) / 1000 > maxUnconnectedStateSeconds
) {
console.log(
"sitting in " +
lastState +
" for longer than " +
maxUnconnectedStateSeconds +
" seconds"
);
//console.log("slack watchdog attempting to force reconnect");
//console.log(this.rtmClient);
}
if (lastState != this.rtmClient.stateMachine.getCurrentState()) {
stateAt = Date.now();
}
lastState = this.rtmClient.stateMachine.getCurrentState();
}, interval);
this.on("close", () => {
clearInterval(intervalId);
});
};
//this.connectionWatchdog();
this.on("close", (done) => {
/**
* attempt a disconnect regardless of current state
* and simply catch invalid transitions etc
*/
if (this.rtmClient.connected) {
this.rtmClient
.disconnect()
.then(() => {
this.rtmClient.removeAllListeners();
done();
})
.catch((e) => {
done();
});
} else {
done();
}
});
}
}
RED.nodes.registerType("slack-config", SlackConfig, {
credentials: {
token: { type: "text" },
},
});
/**
* Send the current state of the config object out
*
* @param {*} n
*/
function SlackState(n) {
RED.nodes.createNode(this, n);
var node = this;
this.client = n.client;
this.clientNode = RED.nodes.getNode(this.client);
node.status(statuses.disconnected);
if (node.client) {
SetConfigNodeConnectionListeners(node);
node.on("input", function (msg, send, done) {
SlackDebug("slack-state incoming message", msg);
// support of 1.0+ and pre-1.0
send =
send ||
function () {
node.send.apply(node, arguments);
};
node.status(statuses.sending);
/**
* support for forcing a refresh of data
*/
if (msg.payload === true) {
node.clientNode
.refreshState()
.then(() => {
msg.slackState = node.clientNode.state;
send(msg);
node.status(statuses.connected);
if (done) {
done();
}
})
.catch((e) => {
SlackDebug("slack-state error response", e.data);
msg.payload = e.data;
send(msg);
node.status(statuses.connected);
if (done) {
done();
}
});
} else {
msg.slackState = node.clientNode.state;
send(msg);
node.status(statuses.connected);
if (done) {
done();
}
}
});
["state_initialized"].forEach((eventName) => {
node.clientNode.on(eventName, (e) => {
node.status(statuses.sending);
var msg = {};
switch (eventName) {
case "state_initialized":
eventName = "ready";
break;
}
msg.slackState = node.clientNode.state;
msg.payload = {
type: eventName,
};
node.send([null, msg]);
node.status(statuses.connected);
});
});
} else {