Skip to content

Commit

Permalink
Merge pull request #6 from wbruno/master
Browse files Browse the repository at this point in the history
getToken to fetch by specific day
  • Loading branch information
rafaell-lycan committed Feb 10, 2015
2 parents 2852bad + ee492dc commit cf2f0bb
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 2 deletions.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
});
Expand Down
66 changes: 64 additions & 2 deletions lib/Sabesp.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
Promise = require('promise');

// Our Sabesp url
var token;

var url = 'http://www2.sabesp.com.br/mananciais/DivulgacaoSiteSabesp.aspx';

var dams = {
Expand Down Expand Up @@ -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;
})();

0 comments on commit cf2f0bb

Please sign in to comment.