-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
220 lines (180 loc) · 5.25 KB
/
app.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
var express = require('express'),
//routes = require('./routes'),
http = require('http'),
path = require('path'),
xml2js = require('xml2js'),
moment = require('moment'),
redis,
Cache,
YR;
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
//
// Routes and handlers
//
// Home page
app.get('/', function(req, res){
res.render('index');
});
// Create widget
app.post('/', function(req, res){
var url = req.body.url,
num = req.body.num || 10,
lang = req.body.lang || 'en';
if(!url) {
return res.render('index', {error: "Please enter a valid URL. Example:<br/>http://www.yr.no/place/Sweden/Stockholm/Stockholm/"});
}
url = tidyUrl(url);
res.render('created', {url: url, num: num, lang: lang});
});
// Show forecast data in JSONP format
app.get('/api/forecast', function(req, res) {
if(!req.query.jsonp) {
return res.send(400, "Missig jsonp. Example: ?jsonp=myCallback");
}
return handleShowForecast(req, res, req.query.jsonp);
});
// Show forecast as plain HTML
app.get('/forecast', function(req, res) {
return handleShowForecast(req, res);
});
// Generic handler of forecast that
// outputs HTML or widget
function handleShowForecast(req, res, jsonp) {
var weatherUrl = req.query.url,
limit = req.query.limit || 10;
if(!weatherUrl) {
return res.send(400, "Missing url to forecast xml. Example: ?url=http://www.yr.no/place/Norway/Telemark/Sauherad/Gvarv/forecast.xml");
}
weatherUrl = weatherUrl.replace('http://', '');
Cache.getOrFetch(weatherUrl, function(err, forecast, fromCache) {
if(err) {
return res.send(err);
}
res.setHeader("X-Polman-Cache-Hit", fromCache || false);
res.setHeader("Content-Type", jsonp ? "application/javascript" : "text/html");
res.render(jsonp ? 'forecast-jsonp' : 'forecast', {forecast: forecast, num: limit, moment: moment, jsonp: jsonp});
});
}
// Tidies URL that user posted.
function tidyUrl(url) {
if(url.slice(0,7).toLowerCase() !== 'http://') {
url = 'http://' + url;
}
if(url.indexOf('.xml') === -1) {
if(url.indexOf('/', url.length - 1) === -1) {
url += '/';
}
url += 'forecast.xml';
}
return url;
}
//
// YR client for fetching and parsing data from
// yr.no's web service.
//
YR = {
initialize: function() {
this.parser = new xml2js.Parser({ mergeAttrs: true, explicitArray: false });
},
// Fetch weather data from given url
fetch: function(url, cb) {
var that = this;
http.get({
host: 'www.yr.no',
path: url.slice(url.indexOf('/'), url.length)
}, onResponse).end();
function onResponse(res) {
var body = '';
if(res.status >= 400) {
cb.call(this, "Could not retriev data from " + url + " - are you sure this is a valid URL?");
}
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
that.xmlToJson(body, function(err, json) {
if(err || json['error']) {
cb.call(this, "Error: Could not parse XML from yr.no");
return;
}
json = that.tidyJSON(json);
Cache.set(url, JSON.stringify(json));
cb.call(this, undefined, json);
});
});
res.on('error', function () {
cb.call(this, "Could not fetch data from yr.no");
});
}
},
// Parse XML from yr.no into JSON format
// that can be used when rendering the view.
xmlToJson: function(xml, cb) {
this.parser.parseString(xml, cb);
},
// Tidy JSON object that was automagically
// created from XML
tidyJSON: function(json) {
json.weatherdata.forecast.tabular = json.weatherdata.forecast.tabular.time;
if(json.weatherdata.forecast.text) {
delete json.weatherdata.forecast.text;
}
return json;
}
};
//
// Redis cache.
//
Cache = {
// Cache TTL/expiry in seconds
ttl: 60*15,
initialize: function() {
if (process.env.REDISTOGO_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL);
redis = require("redis").createClient(rtg.port, rtg.hostname);
redis.auth(rtg.auth.split(":")[1]);
} else {
redis = require("redis").createClient();
}
},
getOrFetch: function(key, cb) {
redis.get(key, function(err, forecast) {
if(forecast) {
// Hit from cache
cb.call(this, undefined, JSON.parse(forecast), true);
} else {
// Go ask yr.no about the forecast
YR.fetch(key, cb);
}
});
},
set: function(key, value) {
var that = this;
redis.set(key, value, function() {
redis.expire(key, that.ttl);
});
}
};
//
// Create and start server :)
//
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
Cache.initialize();
YR.initialize();
});