Fix fallback JSON
[KiwiIRC.git] / server / httphandler.js
1 var url = require('url'),
2 fs = require('fs'),
3 node_static = require('node-static'),
4 _ = require('lodash');
5
6
7
8 var HttpHandler = function (config) {
9 var public_html = config.public_html || 'client/';
10 this.file_server = new node_static.Server(public_html);
11 };
12
13 module.exports.HttpHandler = HttpHandler;
14
15
16
17 HttpHandler.prototype.serve = function (request, response) {
18 // The incoming requests base path (ie. /kiwiclient)
19 var base_path = global.config.http_base_path || '/kiwi',
20 base_path_regex;
21
22 // Trim of any trailing slashes
23 if (base_path.substr(base_path.length - 1) === '/') {
24 base_path = base_path.substr(0, base_path.length - 1);
25 }
26
27 // Build the regex to match the base_path
28 base_path_regex = base_path.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
29
30 // Any asset request to head into the asset dir
31 request.url = request.url.replace(base_path + '/assets/', '/assets/');
32
33 // Any requests for /client to load the index file
34 if (request.url.match(new RegExp('^' + base_path_regex + '([/$]|$)', 'i'))) {
35 request.url = '/';
36 }
37
38 // If the 'magic' translation is requested, figure out the best language to use from
39 // the Accept-Language HTTP header. If nothing is suitible, serve an empty response,
40 // Kiwi will just use the default en-gb strings baked in to it.
41 if (request.url === '/assets/locales/magic.json') {
42 return serveMagicLocale.call(this, request, response);
43 }
44
45 this.file_server.serve(request, response, function (err) {
46 if (err) {
47 response.writeHead(err.status, err.headers);
48 response.end();
49 }
50 });
51 };
52
53 var serveMagicLocale = function (request, response) {
54 var langs = [],
55 available = [],
56 i = 0;
57 if (request.headers['accept-language']) {
58 // Example: en-gb,en;q=0.5
59 langs = request.headers['accept-language'].split(',');
60 available = (function () {
61 var files = [],
62 l = [];
63 files = fs.readdirSync('client/assets/locales');
64 files.forEach(function (file) {
65 if (file.slice(-5) === '.json') {
66 l.push(file.slice(0, -5));
67 }
68 });
69 return l;
70 })();
71 for (i = 0; i < langs.length; i++) {
72 langs[i] = langs[i].split(';q=');
73 langs[i][1] = (typeof langs[i][1] === 'string') ? parseFloat(langs[i][1]) : 1.0;
74 }
75 langs.sort(function (a, b) {
76 return b[1] - a[1];
77 });
78
79 for (i = 0; i < langs.length; i++) {
80 if (langs[i][0] === '*') {
81 break;
82 } else if (_.contains(available, langs[i][0])) {
83 return this.file_server.serveFile('/assets/locales/' + langs[i][0] + '.json', 200, {Vary: 'Accept-Language', 'Content-Language': langs[i][0]}, request, response);
84 }
85 }
86 }
87
88 response.writeHead(200, {
89 'Vary': 'Accept-Language',
90 'Content-Type': 'application/json',
91 'Content-Language': 'en-gb'
92 });
93 response.end('{"en-gb": {"":{}}}');
94 };