diff --git a/index.js b/index.js index f06deb8..9450000 100644 --- a/index.js +++ b/index.js @@ -14,6 +14,12 @@ }); }); + app.get('/:date', function (req, res) { + Sabesp.fetch(req.params.date).then(function(resolve, reject) { + res.json(resolve); + }); + }); + app.listen(app.get('port'), function () { console.log('Magic happens on port: ' + app.get('port')); }); diff --git a/lib/Sabesp.js b/lib/Sabesp.js index 6abc174..f2b3a4a 100644 --- a/lib/Sabesp.js +++ b/lib/Sabesp.js @@ -5,6 +5,8 @@ Promise = require('promise'); // Our Sabesp url + var token; + var url = 'http://www2.sabesp.com.br/mananciais/DivulgacaoSiteSabesp.aspx'; var dams = { @@ -61,18 +63,78 @@ return json; } + function _buildData(date, token) { + date = date.split('-'); + + return { + "__VIEWSTATE": token.state, + "__EVENTVALIDATION": token.validation, + "Imagebutton1.x": 8, + "Imagebutton1.y": 6, + "cmbDia": parseInt(date[2], 10), + "cmbMes": parseInt(date[1], 10), + "cmbAno": parseInt(date[0], 10) + }; + } + + var Sabesp = {}; - Sabesp.fetch = function() { + Sabesp.fetch = function(date) { + if (date) { + return new Promise(function(resolve, reject) { + var data = _buildData(date, token); + + request({ + 'url': url, + 'method': 'POST', + 'headers': { + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*-/*;q=0.8', + 'Host': 'www2.sabesp.com.br', + 'Origin': 'http://www2.sabesp.com.br', + 'Referer': url, + 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.114 Safari/537.36', + }, + 'jar': true, + 'form': data, + }, function(error, response, html){ + resolve(_parserHTML(html)); + } + ); + + }); + } else { + return new Promise(Sabesp.today); + } + }; + Sabesp.today = function(resolve, reject) { + request(url, function (error, response, html) { + if (error) { + reject(error); + } else { + resolve(_parserHTML(html)); + } + }); + }; + Sabesp.getToken = function() { return new Promise(function(resolve, reject) { request(url, function (error, response, html) { if (error) { reject(error); } else { - resolve(_parserHTML(html)); + var $ = cheerio.load(html), + ret = { + state: $('#__VIEWSTATE').val(), + validation: $('#__EVENTVALIDATION').val() + }; + resolve(ret); } }); }); }; + Sabesp.getToken().then(function(resolve, reject) { + token = resolve; + }); + module.exports = Sabesp; })();