This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.js
237 lines (205 loc) · 7.21 KB
/
server.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
const express = require('express');
const createError = require('http-errors');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const compression = require('compression');
const logger = require('morgan');
const fs = require('fs');
const path = require('path');
const rfs = require('rotating-file-stream');
const pjson = require('./package.json');
const request = require('request-promise');
require('dotenv').config();
process.env.APP_ENV === 'dev' ? process.env.NODE_ENV = 'development' : process.env.NODE_ENV = 'production';
const app = express();
/** Configure OpenWeather **/
const openWeatherSettings = {
url: 'https://api.openweathermap.org/data/2.5/onecall',
api_key: process.env.OPENWEATHER_API_KEY,
};
/** Configure Netatmo API **/
const netatmoSettings = {
url: 'https://api.netatmo.com/',
client_id: process.env.NETATMO_CLIENT_ID,
client_secret: process.env.NETATMO_CLIENT_SECRET
};
/** Logs configuration **/
// Set logs directory
const logsDir = path.join(__dirname, 'logs');
// Ensure logs directory exists
fs.existsSync(logsDir) || fs.mkdirSync(logsDir);
// Create a rotating write stream
const accessLogStream = rfs.createStream('access.log', {
interval: '1d', // rotate daily
path: logsDir
});
/** View engine setup **/
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/** Express configuration **/
app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger(
process.env.APP_ENV === 'dev' ? process.env.APP_ENV : 'combined',
process.env.APP_ENV === 'dev' ? null : {stream: accessLogStream}
));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res, next) => {
let keywords = '';
pjson.keywords.map((keyword, index) => keywords += index !== 0 ? `, ${keyword}` : keyword);
res.render('index', {
title: pjson.name,
description: pjson.description,
version: pjson.version,
author: pjson.author,
keywords: keywords
});
});
/** Request promise handler **/
const handleRequestPromise = (res, next, options) => {
request(options)
.then(result => {
return res.json(result)
})
.catch(error => {
console.log(error)
// If no error we still want to check the status code
if (error.statusCode !== 500) {
const exception = error.error;
return res.status(error.statusCode).json({status: 'error', msg: exception.message});
}
return next(error);
});
};
app.post('/netatmo-auth', (req, res, next) => {
// We want to verify that each needed parameters are set in the request
const {username, password, secret} = req.body;
if (!username || !password || !secret) return res.status(400).json({status: 'error', msg: 'Bad request'});
// We want to check if the secret key is correct
// TODO : may be add a database or a file to manage multiple keys and revoke any access
if (secret !== process.env.APP_SECRET) return res.status(401).json({status: 'error', msg: 'Bad login'});
const options = {
method: 'POST',
uri: `${netatmoSettings.url}oauth2/token`,
form: {
client_id: netatmoSettings.client_id,
client_secret: netatmoSettings.client_secret,
grant_type: 'password',
scope: 'read_station',
username: username,
password: password
},
json: true
};
handleRequestPromise(res, next, options);
});
app.post('/netatmo-refresh-token', (req, res, next) => {
// We want to verify that each needed parameters are set in the request
const refresh_token = req.body.refresh_token;
if (!refresh_token) return res.status(400).json({status: 'error', msg: 'Bad request'});
const options = {
method: 'POST',
uri: `${netatmoSettings.url}oauth2/token`,
form: {
client_id: netatmoSettings.client_id,
client_secret: netatmoSettings.client_secret,
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
handleRequestPromise(res, next, options);
});
app.post('/netatmo-station-data', (req, res, next) => {
// We want to verify that each needed parameters are set in the request
const access_token = req.body.access_token;
if (!access_token) return res.status(400).json({status: 'error', msg: 'Bad request'});
const options = {
uri: `${netatmoSettings.url}api/getstationsdata`,
qs: {
access_token: access_token
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true
};
handleRequestPromise(res, next, options);
});
app.post('/netatmo-measure', (req, res, next) => {
// We want to verify that each needed parameters are set in the request
const {access_token, device_id, module_id, scale, type, date_begin, date_end} = req.body;
if (!access_token ||
!device_id ||
!module_id ||
!scale ||
!type ||
!date_begin ||
!date_end ) return res.status(400).json({status: 'error', msg: 'Bad request'});
const options = {
uri: `${netatmoSettings.url}api/getmeasure`,
qs: {
access_token: access_token,
device_id: device_id,
module_id: module_id,
scale: scale,
type: type,
date_begin: date_begin,
date_end: date_end,
optimize: 'false'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true
};
handleRequestPromise(res, next, options);
});
app.get('/openweather/:latitude/:longitude/:lang/:units', (req, res, next) => {
// We want to verify that each needed parameters are set in the request
let {latitude, longitude, units, lang} = req.params;
if (!latitude || !longitude || !lang || !units) return res.status(400).json({status: 'error', msg: 'Bad request'});
// Bind netatmo unit to openweather unit
if (units === 'si') {
units = 'metric'
} else {
units = 'imperial'
}
const options = {
uri: openWeatherSettings.url,
qs: {
lat: latitude,
lon: longitude,
units: units,
lang: lang,
appid: openWeatherSettings.api_key
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true
};
handleRequestPromise(res, next, options);
});
/** Catch 404 and forward to error handler **/
app.use((req, res, next) => {
next(createError(404));
});
/** Errors handler **/
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000 as ' + process.env.NODE_ENV)
});