This repository was archived by the owner on Apr 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·436 lines (386 loc) · 9.8 KB
/
cli.js
File metadata and controls
executable file
·436 lines (386 loc) · 9.8 KB
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
#!/usr/bin/env node
'use strict';
const Configstore = require('configstore');
const meow = require('meow');
const axios = require('axios');
const opn = require('opn');
const inquirer = require('inquirer');
const Table = require('cli-table3');
const grid = new Table();
const ora = require('ora');
const chalk = require('chalk');
const boxen = require('boxen');
const checkForUpdate = require('update-check');
const pkg = require('./package.json');
const conf = new Configstore(pkg.name, {
apikey: '',
lang: 'en',
units: 'si',
current: '',
cities: {},
});
const weekday = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
];
const cli = meow(
`
Usage
$ ds <input>
Options
--current -c Show current weather
--today -t Show todays weather
--week -w Show weekly weather
--add -a Add new location
--get -g Get saved location
--delete -d Delete saved location
--settings -s Show Settings JSON
--version -v Show version
--help -h Show help
`,
{
flags: {
current: { alias: 'c' },
today: { alias: 't' },
week: { alias: 'w' },
add: { alias: 'a' },
get: { alias: 'g' },
delete: { alias: 'd' },
settings: { alias: 's' },
version: { alias: 'v' },
help: { alias: 'h' },
},
autoVersion: false,
}
);
/* CHECK API KEY AND INPUT */
if (conf.get('apikey') === '') {
addAPIKey();
} else {
checkInput();
}
/* API KEY SET */
function addAPIKey() {
ora('You need DarkSky API Key to continue').fail();
ora('You can get one free from https://darksky.net/dev\n').info();
inquirer
.prompt([
{
message: 'DarkSky API Key',
type: 'input',
name: 'key',
},
])
.then(answers => {
conf.set('apikey', answers.key);
});
}
/* INPUT FLAGS */
function checkInput() {
if (cli.flags.a) {
addCity();
} else if (cli.flags.g) {
const cities = conf.get('cities');
const cityCount = Object.keys(cities).length;
if (cityCount === 0) {
ora('No localiton registered. Please add a localiton first').fail();
return;
}
getCities(cities);
} else if (cli.flags.d) {
const cities = conf.get('cities');
const cityCount = Object.keys(cities).length;
if (cityCount === 0) {
ora('No location registered to delete').fail();
return;
}
removeCity(cities);
} else if (cli.flags.s) {
console.log('Opening settings file: ' + chalk.magenta.bold(conf.path));
opn(conf.path, { wait: false });
} else if (cli.flags.c || cli.flags.t || cli.flags.w) {
if (conf.get('current') === '') {
ora('Please select a location first').fail();
return;
}
fecthWeather();
} else if (cli.flags.v) {
checkUpdates();
} else {
cli.showHelp();
}
}
/* CHECK UPDATES */
async function checkUpdates() {
let update = null;
try {
update = await checkForUpdate(pkg);
} catch (error) {
console.log(chalk.red('\nFailed to check for updates:'));
console.error(error);
}
let updateText;
let commandText;
if (update) {
updateText =
'Update available ' +
chalk.gray(pkg.version) +
' → ' +
chalk.green(update.latest);
commandText =
'Run ' + chalk.cyan('npm i -g ' + pkg.name) + ' to update';
} else {
updateText = 'You are using the latest version';
commandText = pkg.name + ' v' + pkg.version;
}
console.log(
boxen(updateText + '\n' + commandText, {
padding: 1,
margin: 1,
align: 'center',
})
);
}
/* SETTINGS */
function addCity() {
inquirer
.prompt([
{
message: 'City Name:',
type: 'input',
name: 'name',
},
{
message: 'Latitude:',
type: 'input',
name: 'lat',
},
{
message: 'Longitude',
type: 'input',
name: 'lon',
},
{
message: 'Are your choices correct?',
type: 'list',
name: 'isConfirmed',
choices: ['Yes', 'No'],
},
])
.then(answers => {
if (answers.isConfirmed === 'No') {
addCity();
} else {
conf.set('cities.' + answers.name + '.lat', answers.lat);
conf.set('cities.' + answers.name + '.lon', answers.lon);
conf.set('current', answers.name);
}
});
}
function getCities(cities) {
inquirer
.prompt([
{
message: 'Switch to a city',
type: 'list',
name: 'cityName',
choices: Object.keys(cities),
},
])
.then(answers => {
conf.set('current', answers.cityName);
});
}
function removeCity(cities) {
inquirer
.prompt([
{
message: 'Delete a city',
type: 'list',
name: 'cityName',
choices: Object.keys(cities),
},
])
.then(answers => {
conf.set('current', '');
conf.delete('cities.' + answers.cityName);
});
}
/* FETCH AND WRITE WEATHER */
function fecthWeather() {
let exclude = '';
let spinner = ora();
if (cli.flags.c) {
exclude = '&exclude=hourly,minutely,daily,weekly,flags,alerts';
spinner = ora('Fetching DarkSky For Current Weather').start();
} else if (cli.flags.t) {
exclude = '&exclude=daily,minutely,flags,alerts';
spinner = ora('Fetching DarkSky For Daily Weather').start();
} else if (cli.flags.w) {
exclude = '&exclude=hourly,minutely,currently,flags,alerts';
spinner = ora('Fetching DarkSky For Weekly Weather').start();
}
const cityName = conf.get('current');
const cityData = conf.get('cities.' + cityName);
const request =
'https://api.darksky.net/forecast/' +
conf.get('apikey') +
'/' +
cityData.lat +
',' +
cityData.lon +
'?lang=' +
conf.get('lang') +
'&units=' +
conf.get('units') +
exclude;
axios
.get(request)
.then(response => {
spinner.succeed('Fetching DarkSky Data Succeeded');
writeWeather(response.data, cityName);
})
.catch(error => {
spinner.fail('Error Fetching DarkSky Data');
console.log(error);
});
}
function writeWeather(response, cityName) {
// Set Title
grid.push([
chalk.green.bold(cityName),
chalk.green.bold('Temperature'),
chalk.green.bold('Precipation'),
chalk.green.bold('Pressure'),
chalk.green.bold('Wind'),
chalk.green.bold('Clouds'),
chalk.green.bold('UV'),
chalk.green.bold('Summary'),
]);
if (cli.flags.c) {
pushData(response.currently, response.currently);
} else if (cli.flags.t) {
for (let index = 0; index < 25; index++) {
const day = response.hourly.data[index];
const previousDay =
index === 0 ? day : response.hourly.data[index - 1];
pushData(day, previousDay);
}
} else if (cli.flags.w) {
for (let index = 0; index < response.daily.data.length; index++) {
const day = response.daily.data[index];
const previousDay =
index === 0 ? day : response.daily.data[index - 1];
pushData(day, previousDay);
}
}
console.log(grid.toString());
}
function pushData(day, previousDay) {
grid.push([
getDayName(day.time),
getTemperature(day),
getPrecip(day),
getPressure(day.pressure, previousDay.pressure),
getWind(day.windSpeed, day.windBearing),
getClouds(day.cloudCover),
getUV(day.uvIndex),
day.summary,
]);
}
/* GET FUNCTIONS */
function getDayName(time) {
const d = new Date(time * 1000);
if (cli.flags.c) {
return chalk.green.bold('Current');
}
if (cli.flags.t) {
return chalk.green.bold(
pad(d.getHours(), '0') + ':' + pad(d.getMinutes(), '0')
);
}
return chalk.green.bold(weekday[d.getDay()]);
}
function getTemperature(day) {
if (cli.flags.w) {
return (
formatTemperature(day.temperatureMin) +
' - ' +
formatTemperature(day.temperatureMax)
);
}
return formatTemperature(day.temperature);
}
function getPrecip(day) {
if (day.precipProbability === 0) return '';
let precipType;
const precipProbability = pad(round(day.precipProbability * 100), ' ');
const shouldColorize = precipProbability >= 25;
if (day.precipType === 'rain') {
precipType = shouldColorize
? (precipType = chalk.blue('(Rain)'))
: '(Rain)';
} else if (day.precipType === 'sleet') {
precipType = shouldColorize
? (precipType = chalk.blue('(Sleet)'))
: '(Sleet)';
} else if (day.precipType === 'snow') {
precipType = shouldColorize
? (precipType = chalk.blue('(Snow)'))
: '(Snow)';
}
return precipProbability + '% ' + precipType;
}
function getPressure(pressure, prevPressure) {
if (pressure > prevPressure)
return chalk.red('↑ ') + round(pressure) + ' hPa';
if (pressure < prevPressure)
return chalk.blue('↓ ') + round(pressure) + ' hPa';
return '• ' + round(pressure) + ' hPa';
}
function getWind(speed, bearing) {
if (bearing >= 292.5 && bearing < 337.5) return '↘ ' + speed + ' kph';
if (bearing >= 247.5 && bearing < 292.5) return '→ ' + speed + ' kph';
if (bearing >= 202.5 && bearing < 247.5) return '↗ ' + speed + ' kph';
if (bearing >= 157.5 && bearing < 202.5) return '↑ ' + speed + ' kph';
if (bearing >= 112.5 && bearing < 157.5) return '↖ ' + speed + ' kph';
if (bearing >= 67.5 && bearing < 112.5) return '← ' + speed + ' kph';
if (bearing >= 22.5 && bearing < 67.5) return '↙ ' + speed + ' kph';
if (bearing > 337.5 && bearing < 22.5) return '↓ ' + speed + ' kph';
return '';
}
function getClouds(cloudCoverage) {
return pad(round(cloudCoverage * 100), ' ') + '%';
}
function getUV(uv) {
if (uv <= 2) return chalk.hex('#6bbf30')(uv);
if (uv >= 3 && uv < 5) return chalk.hex('#ffd208')(uv);
if (uv >= 5 && uv < 7) return chalk.hex('#ffae00')(uv);
if (uv >= 7 && uv < 10) return chalk.hex('#ea3447')(uv);
if (uv >= 10) return chalk.hex('#a44c6f')(uv);
return uv;
}
/* FORMAT HELPERS */
function formatTemperature(temp) {
temp = round(temp);
if (temp <= 0) return chalk.cyan(temp + '°c');
if (temp >= 1 && temp < 10) return chalk.cyan(temp + '°c');
if (temp >= 10 && temp < 15) return chalk.blue(temp + '°c');
if (temp >= 15 && temp < 20) return chalk.white(temp + '°c');
if (temp >= 20 && temp < 25) return chalk.white(temp + '°c');
if (temp >= 25 && temp < 30) return chalk.yellow(temp + '°c');
if (temp >= 30) return chalk.red(temp + '°c');
return temp + '°c';
}
function round(number) {
const value = (number * 2).toFixed() / 2;
return value.toFixed();
}
function pad(num, add) {
return (add + num).slice(-2);
}