forked from nimbella/command-sets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
times.js
212 lines (199 loc) · 5.59 KB
/
times.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
/* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */
// jshint esversion: 9
const makeStringOfLength = (string, length) => {
while (string.length < length) {
string += ' ';
}
return string;
};
/**
* A small function that converts slack `section` to mattermost compatible markdown.
* @param {object} element - Slack element
* @param {string} client - name of the client
* @returns {string}
*/
const mui = (element, client) => {
if (client === 'mattermost') {
const output = [];
switch (element.type) {
case 'context': {
for (const item of element.elements) {
output.push(item.text.replace(/\*/g, '**'));
}
break;
}
case 'section': {
if (element.fields && element.fields.length > 0) {
let longestColumn = 0;
for (let i = 0; i < element.fields.length; i++) {
element.fields[i].text = element.fields[i].text.replace(/\*/g, '**');
if (element.fields[i].text.length > longestColumn) {
longestColumn = element.fields[i].text.length;
}
}
// Customized for this command to append two fields into one string of equal length
for (let i = 0; i < element.fields.length; i += 2) {
const cityName = makeStringOfLength(
element.fields[i].text,
longestColumn
);
const cityTime = element.fields[i + 1].text;
output.push(cityName + ' ' + cityTime + '\n');
}
} else if (element.text) {
// Convert single text element to h4 in mattermost.
output.push('#### ' + element.text.text.replace(/\*/g, '**'));
}
break;
}
}
return output.join('');
}
return element;
};
const defaultCities = 'delhi, rome, new york, los angeles';
const worldClock1 = 'https://24timezones.com/current_world_time.php/';
const worldClock2 = 'https://www.timeanddate.com/worldclock/full.html/';
const axios = require('axios');
const cheerio = require('cheerio');
const tableparser = require('cheerio-tableparser');
const toTitleCase = (phrase) =>
phrase
.trim()
.toLowerCase()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
const abbrExpand = (shortName) => {
let longName = shortName;
switch (shortName) {
case 'Delhi':
longName = 'New Delhi';
break;
default:
break;
}
return longName;
};
const fail = (err) => {
console.log(err);
return {
response_type: 'in_channel',
text: err || "Couldn't get times.",
};
};
const success = (fields, client) => {
const response = {
response_type: 'in_channel',
blocks: []
};
const body = {
type: 'section',
fields: []
}
Object.keys(fields).forEach((key) => {
body.fields.push(
{
type: 'mrkdwn',
text: `*${key}*`,
},
{
type: 'mrkdwn',
text: `*${fields[key].split('\n')[0]}*`,
}
);
});
const footer = {
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `add _times_ to your ${client} with <${client === 'slack' ? 'https://nimbella.com/blog/see-the-time-in-different-cities-on-slack-with-nimbella-commander/' : 'https://github.com/nimbella/command-sets/tree/master/times'}|Commander>.`,
},
],
}
response.blocks.push(mui(body, client))
response.blocks.push(mui(footer, client))
if (client === 'mattermost') {
response.text = response.blocks.join('\n');
delete response.blocks;
}
return response;
};
/**
* @description current time for the given cities
* @param {ParamsType} params list of command parameters
* @param {?string} commandText text message
* @param {!object} [secrets = {}] list of secrets
* @return {Promise<SlackBodyType>} Response body
*/
async function _command(params, commandText, secrets = {}) {
let response;
try {
response = await axios
.get(worldClock1, {
headers: {
'Accept-Language': 'en-US,en;q=0.9',
},
})
.catch((error) => {
console.error(error);
axios.get(worldClock2);
});
if (response.status !== 200) {
return fail(response);
}
} catch (err) {
return fail(err.message);
}
const fields = {};
const html = cheerio.load(response.data);
const { cities = defaultCities } = params;
const cityList = cities.split(',');
try {
tableparser(html);
const times = html('table').parsetable(false, false, true);
let allTimes = [];
let allCities = [];
if (times.length > 0) {
for (let index = 0; index < times.length; index += 1) {
allCities = allCities.concat(times[index]);
allTimes = allTimes.concat(times[index + 1]);
index += 1;
}
}
for (let index = 0; index < cityList.length; index += 1) {
const element = cityList[index];
let city = toTitleCase(element);
city = abbrExpand(city);
let time;
const recordIndex = allCities.findIndex((e) => e.startsWith(city));
if (recordIndex > 0) {
time = allTimes[recordIndex];
} else {
time = 'NA';
}
fields[city] = time;
}
return success(fields, params.__client.name);
} catch (e) {
return fail(e.message);
}
}
/**
* @typedef {object} SlackBodyType
* @property {string} text
* @property {'in_channel'|'ephemeral'} [response_type]
*/
const main = async (args) => ({
body: await _command(
args.params,
args.commandText,
args.__secrets || {}
).catch((error) => ({
response_type: 'ephemeral',
text: `Error: ${error.message}`,
})),
});
module.exports = main;