-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
271 lines (248 loc) · 7.88 KB
/
index.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
'use strict';
var domain = require('domain');
var request = require('request');
var cheerio = require('cheerio');
var async = require('async');
var unorm = require('unorm');
var lodash = require('lodash');
var url = require('url');
var spots = require('./spots.json');
var icons = require('./icons.json');
function normalizeString(str){
var combining = /[\u0300-\u036F]/g;
return unorm.nfkd(str).replace(combining, '');
}
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
function translateIcon(value) {
return icons[value] || null;
}
var tempSymbol = String.fromCharCode(65533); // latin1 temperature symbol
var defaults = {
target_url: 'http://www.smn.gov.ar/',
};
function live(id, options, callback){
if (typeof options == 'function') {
callback = options;
options = {};
}
lodash.defaults(options, defaults);
var prevDomain = process.domain || domain.create();
callback = prevDomain.bind(callback);
domain
.create()
.on('error', callback)
.run(function(){
request.get({
url: url.resolve(options.target_url, 'mobile/estado_movil.php'),
qs: {
ciudad: id.split("-")[1]
}
}, function(err, res, data){
if (err) {
return callback(err);
}
if (/Sin informac/.test(data)) {
return callback();
}
var $ = cheerio.load(data);
var data = {
id: id,
temperature: parseFloat($('.temp_grande').text().split(tempSymbol)[0]),
feelsLike: parseFloat($('table.texto_temp_chico tr').slice(0, 1).find('td').slice(-1).text().split(tempSymbol)[0]) || null,
visibility: $('table.texto_temp_chico tr').slice(1, 2).find('td').slice(-1).text(),
humidity: parseFloat($('table.texto_temp_chico tr').slice(2, 3).find('td').slice(-1).text().trim().split(' ')[0]),
pressure: parseFloat($('table.texto_temp_chico tr').slice(3, 4).find('td').slice(-1).text().split(' ')[0]),
windSpeed: $('table.texto_temp_chico tr').slice(4, 5).find('td').slice(-1).text(),
status: $('.temp_texto').text(),
icon: translateIcon($('img[width=120px]').attr('src'))
};
var numberFields = ['temperature', 'feelsLike', 'humidity', 'pressure'];
var stringFields = ['visibility', 'windSpeed', 'status', 'icon'];
lodash.values(lodash.pick(data, numberFields)).forEach(function(x){
if (isNaN(x)) {
throw new Error("Parsing error: " + JSON.stringify(data));
}
});
lodash.values(lodash.pick(data, stringFields)).forEach(function(x){
if (!x) {
throw new Error("Parsing error: " + JSON.stringify(data));
}
});
callback(null, data);
});
});
}
function forecast(id, options, callback){
if (typeof options == 'function') {
callback = options;
options = {};
}
lodash.defaults(options, defaults);
var prevDomain = process.domain || domain.create();
callback = prevDomain.bind(callback);
var spot = lodash.find(spots, {id: id});
domain
.create()
.on('error', callback)
.run(function(){
request.get({
url: url.resolve(options.target_url, '/mobile/pronostico_movil.php'),
qs: {
provincia: id.split("-")[0],
ciudad: id.split("-")[1]
}
}, function(err, res, data){
if (err) {
throw err;
}
// Common error
if (/Undefined variable/.test(data)) {
throw new Error("Parsing error.");
}
var $ = cheerio.load(data);
var forecast = $('[name=prondia],[id=pron2]').map(function(){
var dayCode = $(this).find('table td').slice(0, 1).text();
var rows = $(this).find('table').slice(-1).find('tr');
// if only forecast for afternoon (same day forecast)
if (rows.length == 3) {
var afternoonIcon = $(this).find('h5').slice(0, 1).find('img').attr('src')//.split('/').slice(-1)[0].split(".")[0];
return {
dayCode: dayCode,
afternoonIcon: translateIcon(afternoonIcon),
afternoonDescription: $(this).find('p.texto_blanco').slice(0, 1).text(),
};
// else if forecast for morning and afternoon (any other day)
} else if (rows.length == 5) {
var morningIcon = $(this).find('h5').slice(0, 1).find('img').attr('src')//.split('/').slice(-1)[0].split(".")[0];
var afternoonIcon = $(this).find('h5').slice(1, 2).find('img').attr('src')//.split('/').slice(-1)[0].split(".")[0];
return {
dayCode: dayCode,
min: parseFloat(rows.slice(0, 1).find('td').slice(1, 2).text().split('°')[0]),
max: parseFloat(rows.slice(1, 2).find('td').slice(1, 2).text().split('°')[0]),
morningIcon: translateIcon(morningIcon),
afternoonIcon: translateIcon(afternoonIcon),
morningDescription: $(this).find('p.texto_blanco').slice(0, 1).text(),
afternoonDescription: $(this).find('p.texto_blanco').slice(1, 2).text(),
};
} else {
throw new Error("Parsing error.");
}
}).get();
callback(null, {id: id, forecast: forecast});
});
});
}
function noErrors(f){
var me = this;
return function(args){
args = Array.prototype.slice.call(arguments);
var callback = args[args.length - 1];
args[args.length - 1] = function(err, data){
callback(null, err ? null : data);
}
f.apply(me, args);
}
}
function compactResults(callback){
return function(err, data){
callback(null, lodash.compact(data));
}
}
function liveAll(options, callback){
if (typeof options == 'function') {
callback = options;
options = undefined;
}
var ids = lodash.map(lodash.filter(spots, {live: true}), 'id');
async.mapLimit(ids, 5, function(id, callback){
live(id, options, function(err, data){
if (err) return callback();
callback(null, data);
})
}, compactResults(callback));
}
function forecastAll(options, callback){
if (typeof options == 'function') {
callback = options;
options = undefined;
}
var ids = lodash.map(spots, 'id');
async.mapLimit(ids, 5, function(id, callback){
forecast(id, options, function(err, data){
if (err) return callback();
callback(null, data);
})
}, compactResults(callback));
}
function liveWithForecast(options, callback){
if (typeof options == 'function') {
callback = options;
options = undefined;
}
liveAll(options, function(err, liveData){
if (err) {
return callback(err);
}
async.map(lodash.map(liveData, 'id'), noErrors(function(id, callback){
forecast(id, options, callback);
}), compactResults(function(err, forecastData){
var res = lodash.values(lodash.merge(lodash.keyBy(liveData, 'id'), lodash.keyBy(forecastData, 'id')));
callback(null, res);
}));
});
}
module.exports.live = live;
module.exports.liveAll = liveAll;
module.exports.forecast = forecast;
module.exports.forecastAll = forecastAll;
module.exports.liveWithForecast = liveWithForecast;
module.exports.spots = spots;
if (module.parent) {
return;
}
/* ICONOS ENCONTRADOS EN EL LIVE */
var liveIcons = require('./liveicons.json');
/* ICONOS ENCONTRADOS EN EL FORECAST */
var foreIcons = require('./foreicons.json');
console.log(spots.length, 'spots');
forecastAll(function(err, data){
console.log("FORECAST");
console.log(data);
console.log(data.length);
return;
var lenBefore = foreIcons.length;
data.forEach(function(spot){
spot.forecast.forEach(function(forecast){
if (forecast.morningIcon) {
foreIcons.push(forecast.morningIcon)
}
if (forecast.afternoonIcon) {
foreIcons.push(forecast.afternoonIcon)
}
})
})
foreIcons = lodash.uniq(foreIcons);
if (lenBefore != foreIcons.length) {
console.log(foreIcons);
console.log(lenBefore, 'iconos antes.', foreIcons.length, 'iconos despues.');
}
require('fs').writeFile('./foreicons.json', JSON.stringify(foreIcons));
});
liveAll(function(err, data){
console.log("LIVE");
console.log(data);
console.log(data.length);
return;
var lenBefore = liveIcons.length;
data.forEach(function(spot){
liveIcons.push(spot.icon);
});
liveIcons = lodash.uniq(liveIcons);
if (lenBefore != liveIcons.length) {
console.log(liveIcons);
console.log(lenBefore, 'iconos antes.', liveIcons.length, 'iconos despues.');
}
require('fs').writeFile('./liveicons.json', JSON.stringify(liveIcons));
});