-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
147 lines (123 loc) · 4.42 KB
/
server.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
'use strict';
const Promise = require("bluebird");
const express = require("express");
const expressPromiseRouter = require("express-promise-router");
const path = require("path");
const fs = Promise.promisifyAll(require("fs"));
const defaultValue = require("default-value");
const unhandledError = require("unhandled-error");
const config = require("./config.json");
const createThumbnailer = require("./lib/thumbnailer");
const createPhotoManager = require("./lib/photo-manager");
const validatePhotoFilename = require("./lib/validate/photo-filename");
const validateDateFolderName = require("./lib/validate/date-folder");
const validateNumber = require("./lib/validate/number");
const ValidationError = require("./lib/validate/error");
const ThumbnailError = require("./lib/thumbnailer/error");
let errorHandler = unhandledError((err, context) => {
console.log("Unhandled error!", err);
});
let thumbnailer = createThumbnailer(path.join(__dirname, "thumbnails"), config.pictureFolder, {width: config.thumbnails.width, height: config.thumbnails.height, quality: config.thumbnails.quality});
let photoManager = createPhotoManager({
photoPath: config.pictureFolder,
paginationThreshold: config.paginationThreshold
});
let app = express();
app.locals.pathPrefix = config.pathPrefix;
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));
// NOTE: This means that any proxied IP header is trusted! While the client IP is not currently used anywhere, this means that anyone who can connect to the service directly can spoof their IP.
app.set("trust proxy", true);
app.use(express.static(path.join(__dirname, "public")));
app.use("/photos", express.static(config.pictureFolder));
let router = expressPromiseRouter();
router.get("/latest", (req, res) => {
return Promise.try(() => {
if (req.query.amount != null) {
validateNumber(req.query.amount);
}
return photoManager.getPictures();
}).then((pictures) => {
let amount = parseInt(defaultValue(req.query.amount, 3));
res.json({
latest: pictures.slice(0, amount).map((picture) => {
return {
date: picture.date.momentDate.format("YYYY-MM-DD"),
filename: picture.filename,
url: `${config.pathPrefix}/view/${picture.date.date}/${picture.filename}`,
thumbnail: `${config.pathPrefix}/thumbnails/${picture.date.date}/${picture.filename}`
};
})
});
});
});
router.get("/:page?", (req, res) => {
return Promise.try(() => {
if (req.params.page != null) {
validateNumber(req.params.page);
}
return photoManager.getPaginatedDatesWithPictures();
}).then((dates) => {
let pageParam = defaultValue(req.params.page, 1);
let pageNumber = parseInt(pageParam) - 1;
if (pageNumber < 0 || pageNumber > dates.length - 1) {
res.status(404).send("404 not found");
} else {
res.render("index", {
dates: dates[pageNumber],
currentPage: pageNumber + 1,
totalPages: dates.length
});
}
});
});
router.get("/view/:date/:filename", (req, res) => {
return Promise.try(() => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);
return photoManager.getPicture(req.params.date, req.params.filename);
}).then((photo) => {
if (photo == null) {
res.status(404).send("404 not found");
} else {
res.render("view", {
photo: photo,
previousPhoto: photo.previous,
nextPhoto: photo.next,
// NOTE: The below does not currently work when the user-facing HTTPd is running on a non-standard port!
absoluteThumbnail: `${req.protocol}://${req.host}${config.pathPrefix}/thumbnails/${photo.date.date}/${photo.filename}`
});
}
});
});
router.get("/thumbnails/:date/:filename", (req, res) => {
return Promise.try(() => {
validateDateFolderName(req.params.date);
validatePhotoFilename(req.params.filename);
return thumbnailer(req.params.date, req.params.filename);
}).then((stream) => {
stream.pipe(res);
}).catch((err) => {
if (/Unable to open file/.test(err.message)) {
res.status(404).send("404 not found");
} else {
throw err;
}
});
});
app.use(router);
app.use((err, req, res, next) => {
if (err instanceof ValidationError) {
res.status(404).send("404 not found");
} else if (err instanceof ThumbnailError) {
res.status(500).send("Failed to generate thumbnail - not an image file?");
} else {
errorHandler.report(err, {
req: req,
res: res
});
}
});
app.listen(config.listen.port, () => {
console.log(`Server listening on port ${config.listen.port}...`);
});