-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.js
221 lines (165 loc) · 5.12 KB
/
weather.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
const express = require('express')
const { json_status, tomorrow, getDayName } = require('./utils')
// some constants
const API_BASE_URL = 'https://api.weather.gov'
// we need fetch
if (typeof fetch == 'undefined') {
fetch = require('node-fetch')
}
module.exports = class {
constructor(settings) {
this._settings = settings
}
routes() {
const router = express.Router()
router.get('/daily/:day', (req, res, next) => {
this.getDailyForecast(req.params.day)
.then((result) => json_status(res, null, result))
.catch(err => next(err))
})
router.get('/hourly/:hour', (req, res, next) => {
this.getHourlyForecast(req.params.hour)
.then((result) => json_status(res, null, result))
.catch(err => next(err))
})
return router
}
async getDailyForecast(day) {
// we need lowercase
day = day.toLocaleLowerCase()
// get the forecast
let forecast = await this._callApi(`/gridpoints/${this._getLocation()}/forecast`)
// we need to get the right day name
if (day.startsWith('tomorrow')) {
day = day.replace('tomorrow', getDayName(tomorrow()))
}
// log
console.log(`Extracting daily forecast for day=${day}`)
// extract forecast
for (let period of forecast.properties.periods) {
if (period.name.toLocaleLowerCase() == day) {
return this._genPayload(period)
}
}
// if not found
throw new Error(`No forecast found for ${day}`)
}
async getHourlyForecast(hour) {
// we need lowercase
hour = hour.toLocaleLowerCase()
// get the forecast
let forecast = await this._callApi(`/gridpoints/${this._getLocation()}/forecast/hourly`)
// get today date
let day = new Date().getDate()
// am/pm stuff
if (hour.toString().endsWith('am')) {
hour = parseInt(hour.replace('am', ''))
} else if (hour.toString().endsWith('pm')) {
hour = parseInt(hour.replace('pm', '')) + 12
}
// we need to get the right hour
if (hour == 'now') {
hour = new Date().getHours()
} else if (hour.toString().startsWith('+')) {
hour = new Date().getHours() + parseInt(hour)
if (hour > 23) {
hour = hour - 24
day = tomorrow().getDate()
}
} else {
let now = new Date().getHours()
if (hour < now) {
if (now < 12) hour = parseInt(hour) + 12
else day = tomorrow().getDate()
}
}
// pad
day = day.toString().padStart(2, '0')
hour = hour.toString().padStart(2, '0')
// log
console.log(`Extracting hourly forecast for day=${day} hour=${hour}`)
// extract forecast
for (let period of forecast.properties.periods) {
if (period.startTime.includes(`${day}T${hour}:`)) {
return this._genPayload(period)
}
}
// if not found
throw new Error(`No forecast found for ${hour}`)
}
_genPayload(period) {
// text
let forecastText = this._genForecastText(period)
// now the payload
return {
text: forecastText,
forecast: period,
}
}
_genForecastText(period) {
// start with short
let text = `${period.shortForecast}.`
if (this._settings.parts?.forecast == 'detailed' && period.detailedForecast != '') {
text = `${period.detailedForecast}.`
}
// temperature
if (this._settings.parts?.temperature !== false && period.temperature) {
text += ` Temperature: ${this._genTemperatureText(period)}.`
}
// chance of precipitation
if (this._settings.parts?.precipitation !== false && period.probabilityOfPrecipitation) {
text += ` Chance of precipitation: ${period.probabilityOfPrecipitation.value||0}%.`
}
// wind speed
if (this._settings.parts?.wind !== false && period.windSpeed) {
text += ` Wind speed: ${period.windSpeed}.`
}
// done
return text
}
_genTemperatureText(period) {
let temp = period.temperature
let unit = period.temperatureUnit
// if right unit
if (this._settings.temperature?.unit && this._settings.temperature.unit != unit) {
if (unit == 'F') {
// farhenheit to celsius
temp = Math.round((temp -32) * 5/9)
unit = 'C'
} else if (unit == 'C') {
// celsius to farhenheit
temp = Math.round(temp * 9/5 + 32)
unit = 'F'
}
}
// done
return `${temp}°${unit}`
}
_getLocation() {
return `${this._settings.location.gridId}/${this._settings.location.gridX},${this._settings.location.gridY}`
}
async _callApi(path, params) {
// call it
let url = this._getUrl(API_BASE_URL, path, params)
console.log(`GET ${url}`)
let response = await fetch(url, this._getFetchOptions())
// parse and check auth
let json = await response.json();
return json
}
_getUrl(baseUrl, path, params) {
let url = `${baseUrl}${path}`
for (let key in params) {
let sep = url.includes('?') ? '&' : '?'
url += `${sep}${key}=${encodeURIComponent(params[key])}`
}
return url
}
_getFetchOptions() {
return {
headers: {
'User-Agent': '(https://github.com/nbonamy/weather-gov-text, nicolas@bonamy.fr)'
}
}
}
}