Timoney, Daniel (dt5972) | 324ee36 | 2017-02-15 10:37:53 -0500 | [diff] [blame] | 1 | /** |
| 2 | * Copyright 2013, 2014 IBM Corp. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | **/ |
| 16 | var express = require('express'); |
| 17 | var fs = require("fs"); |
| 18 | var events = require("./events"); |
| 19 | var path = require("path"); |
| 20 | |
| 21 | var icon_paths = [path.resolve(__dirname + '/../public/icons')]; |
| 22 | |
| 23 | var settings; // settings has to be global, otherwise variable not in scope for express |
| 24 | |
| 25 | events.on("node-icon-dir",function(dir) { |
| 26 | icon_paths.push(path.resolve(dir)); |
| 27 | }); |
| 28 | |
| 29 | |
| 30 | function setupUI(_settings,app) { |
| 31 | |
| 32 | settings = _settings; |
| 33 | |
| 34 | // Need to ensure the url ends with a '/' so the static serving works |
| 35 | // with relative paths |
| 36 | app.get("/",function(req,res) { |
| 37 | if (req.originalUrl.slice(-1) != "/") { |
| 38 | res.redirect(req.originalUrl+"/"); |
| 39 | } else { |
| 40 | req.next(); |
| 41 | } |
| 42 | }); |
| 43 | |
| 44 | var iconCache = {}; |
| 45 | //TODO: create a default icon |
| 46 | var defaultIcon = path.resolve(__dirname + '/../public/icons/arrow-in.png'); |
| 47 | |
| 48 | app.get("/icons/:icon",function(req,res) { |
| 49 | if (iconCache[req.params.icon]) { |
| 50 | res.sendfile(iconCache[req.params.icon]); // if not found, express prints this to the console and serves 404 |
| 51 | } else { |
| 52 | for (var p=0;p<icon_paths.length;p++) { |
| 53 | var iconPath = path.join(icon_paths[p],req.params.icon); |
| 54 | if (fs.existsSync(iconPath)) { |
| 55 | res.sendfile(iconPath); |
| 56 | iconCache[req.params.icon] = iconPath; |
| 57 | return; |
| 58 | } |
| 59 | } |
| 60 | res.sendfile(defaultIcon); |
| 61 | } |
| 62 | }); |
| 63 | |
| 64 | app.get("/settings", function(req,res) { |
| 65 | var safeSettings = { |
| 66 | httpNodeRoot: settings.httpNodeRoot, |
| 67 | version: settings.version |
| 68 | }; |
| 69 | res.json(safeSettings); |
| 70 | }); |
| 71 | |
| 72 | app.use("/",express.static(__dirname + '/../public')); |
| 73 | |
| 74 | return app; |
| 75 | } |
| 76 | |
| 77 | module.exports = setupUI; |