]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - server.js
Add raw/tar/zip endpoints
[perso/Immae/Projets/Nodejs/Surfer.git] / server.js
1 #!/usr/bin/env node
2
3 'use strict';
4
5 var express = require('express'),
6 morgan = require('morgan'),
7 path = require('path'),
8 fs = require('fs'),
9 archiver = require('archiver'),
10 compression = require('compression'),
11 session = require('express-session'),
12 serveIndex = require('serve-index'),
13 escapeHtml = require('escape-html'),
14 bodyParser = require('body-parser'),
15 cookieParser = require('cookie-parser'),
16 lastMile = require('connect-lastmile'),
17 HttpError = require('connect-lastmile').HttpError,
18 HttpSuccess = require('connect-lastmile').HttpSuccess,
19 multipart = require('./src/multipart'),
20 mkdirp = require('mkdirp'),
21 auth = require('./src/auth.js'),
22 webdav = require('webdav-server').v2,
23 files = require('./src/files.js')(path.resolve(__dirname, process.argv[2] || 'files'));
24
25
26 const ROOT_FOLDER = path.resolve(__dirname, process.argv[2] || 'files');
27 const CONFIG_FILE = path.resolve(__dirname, process.argv[3] || '.config.json');
28
29 // Ensure the root folder exists
30 mkdirp.sync(ROOT_FOLDER);
31
32 var config = {
33 folderListingEnabled: false
34 };
35
36 function getSettings(req, res, next) {
37 res.send({ folderListingEnabled: !!config.folderListingEnabled });
38 }
39
40 function setSettings(req, res, next) {
41 if (typeof req.body.folderListingEnabled === 'undefined') return next(new HttpError(400, 'missing folderListingEnabled boolean'));
42
43 config.folderListingEnabled = !!req.body.folderListingEnabled;
44
45 fs.writeFile(CONFIG_FILE, JSON.stringify(config), function (error) {
46 if (error) return next(new HttpError(500, 'unable to save settings'));
47
48 next(new HttpSuccess(201, {}));
49 });
50 }
51
52 // Load the config file
53 try {
54 console.log(`Using config file at: ${CONFIG_FILE}`);
55 config = require(CONFIG_FILE);
56 } catch (e) {
57 if (e.code === 'MODULE_NOT_FOUND') console.log(`Config file ${CONFIG_FILE} not found`);
58 else console.log(`Cannot load config file ${CONFIG_FILE}`, e);
59 }
60
61 if (typeof config.folderListingEnabled === 'undefined') config.folderListingEnabled = true;
62
63 function isRoot(p) {
64 return path.join(ROOT_FOLDER, p) === path.join(ROOT_FOLDER, '/');
65 }
66
67 function sendArchive(format) {
68 var mime, extension;
69 if (format === "zip") {
70 mime = "application/zip";
71 extension = "zip";
72 } else {
73 mime = "application/tar+gzip";
74 extension = "tar.gz";
75 }
76 return function(req, res, next) {
77 if (isRoot(req.path) || !fs.existsSync(path.join(ROOT_FOLDER, req.path)))
78 return res.status(404).sendFile(__dirname + '/frontend/404.html');
79 res.writeHead(200, {
80 'Content-Type': mime,
81 'Content-disposition': 'attachment; filename=' + path.basename(req.path) + '.' + extension
82 });
83 var archive = archiver(format);
84 archive.pipe(res);
85 archive.directory(path.join(ROOT_FOLDER, req.path), path.basename(req.path))
86 archive.finalize();
87 }
88 }
89
90 function rawTemplate(locals, callback) {
91 var html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>wget/curl friendly directory listing of ';
92 html += locals.directory;
93 html += '</title></head><body><ul>\n';
94 html += locals.fileList.map(function (file) {
95 if (file.name === "..") { return ""; }
96 var isDir = file.stat && file.stat.isDirectory();
97 var fpath = locals.directory.split('/').map(function (c) { return encodeURIComponent(c); });
98 if (!isDir) { fpath.shift(); fpath[0] = ""; }
99 fpath.push(encodeURIComponent(file.name));
100 return '<li><a href="' + escapeHtml(path.normalize(fpath.join('/'))) + '">' + escapeHtml(file.name) + '</a></li>';
101 }).join("\n");
102 html += '\n</ul></body></html>';
103 callback(null, html);
104 };
105
106 // Setup the express server and routes
107 var app = express();
108 var router = new express.Router();
109
110 var webdavServer = new webdav.WebDAVServer({
111 requireAuthentification: true,
112 httpAuthentication: new webdav.HTTPBasicAuthentication(new auth.WebdavUserManager(), 'Cloudron Surfer')
113 });
114
115 webdavServer.setFileSystem('/', new webdav.PhysicalFileSystem(ROOT_FOLDER), function (success) {
116 if (success) console.log(`Mounting webdav resource from: ${ROOT_FOLDER}`);
117 });
118
119 var multipart = multipart({ maxFieldsSize: 2 * 1024, limit: '512mb', timeout: 3 * 60 * 1000 });
120
121 router.post ('/api/login', auth.login);
122 router.post ('/api/logout', auth.verify, auth.logout);
123 router.get ('/api/settings', auth.verify, getSettings);
124 router.put ('/api/settings', auth.verify, setSettings);
125 router.get ('/api/tokens', auth.verify, auth.getTokens);
126 router.post ('/api/tokens', auth.verify, auth.createToken);
127 router.delete('/api/tokens/:token', auth.verify, auth.delToken);
128 router.get ('/api/profile', auth.verify, auth.getProfile);
129 router.get ('/api/files/*', auth.verifyIfNeeded, files.get);
130 router.post ('/api/files/*', auth.verify, multipart, files.post);
131 router.put ('/api/files/*', auth.verify, files.put);
132 router.delete('/api/files/*', auth.verify, files.del);
133
134 app.use('/api/healthcheck', function (req, res) { res.status(200).send(); });
135 app.use(morgan('dev'));
136 app.use(compression());
137 app.use('/api', bodyParser.json());
138 app.use('/api', bodyParser.urlencoded({ extended: false, limit: '100mb' }));
139 app.use('/api', cookieParser());
140 app.use('/api', session({ secret: 'surfin surfin', resave: false, saveUninitialized: false }));
141 app.use(router);
142 app.use(webdav.extensions.express('/_webdav', webdavServer));
143 app.use('/_admin', express.static(__dirname + '/frontend'));
144 app.use('/raw', function serveRaw(req, res, next) {
145 if (isRoot(req.path) || !fs.existsSync(path.join(ROOT_FOLDER, req.path)))
146 return res.status(404).sendFile(__dirname + '/frontend/404.html');
147 serveIndex(ROOT_FOLDER, { template: rawTemplate })(req, res, next);
148 });
149 app.use('/zip', sendArchive("zip"));
150 app.use('/tar', sendArchive("tar"));
151 app.use('/', express.static(ROOT_FOLDER));
152 app.use('/', function welcomePage(req, res, next) {
153 if (config.folderListingEnabled || req.path !== '/') return next();
154 res.status(200).sendFile(path.join(__dirname, '/frontend/welcome.html'));
155 });
156 app.use('/', function (req, res) {
157 if (!config.folderListingEnabled) return res.status(404).sendFile(__dirname + '/frontend/404.html');
158
159 if (!fs.existsSync(path.join(ROOT_FOLDER, req.path))) return res.status(404).sendFile(__dirname + '/frontend/404.html');
160
161 res.status(200).sendFile(__dirname + '/frontend/public.html');
162 });
163 app.use(lastMile());
164
165 var server = app.listen(3000, function () {
166 var host = server.address().address;
167 var port = server.address().port;
168
169 console.log(`Base path: ${ROOT_FOLDER}`);
170 console.log();
171 console.log(`Listening on http://${host}:${port}`);
172
173 auth.init(config);
174 });