-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
99 lines (82 loc) · 2.44 KB
/
index.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
var Boom = require("boom");
var Concat = require("concat-stream");
var Hapi = require("hapi");
var Image = require("imagemagick-stream");
var Joi = require("joi");
var LRU = require("bluebird-lru-cache");
var Promise = require("bluebird");
var Screenshot = require("screenshot-stream");
if (!process.env.RUN_URL) throw new Error("RUN_URL environment variable is required.");
if (!process.env.PORT) throw new Error("PORT environment variable is required.");
var server = new Hapi.Server(process.env.HOST || "0.0.0.0", process.env.PORT);
setTimeout(function () {
server.log('info', 'Server exceeded maximum lifetime, exiting.');
process.exit(0);
}, 1000 * 60 * 60);
var internals = {};
internals.runUrl = process.env.RUN_URL;
internals.prepareShot = function (key) {
var plunkId = key.split("@")[0];
return new Promise(function (resolve, reject) {
var captureStream = Screenshot(internals.runUrl + "/plunks/" + plunkId + "/", "1024x768", {delay: 2});
var resizeStream = Image().resize("480").gravity("NorthWest").crop("480x640").quality(75);
var concatStream = Concat(function (buf) {
if (!buf.length) {
return reject(Boom.serverTimeout("Invalid preview, empty buffer"));
}
resolve(buf);
});
captureStream
.pipe(resizeStream)
.pipe(concatStream)
.on("error", reject);
});
};
internals.cache = LRU({
max: 1024 * 1024 * 256,
length: function (buf) { return buf.length; },
fetchFn: internals.prepareShot,
});
server.route({
method: "GET",
path: "/{plunkId}.png",
config: {
cache: {
expiresIn: 1000 * 60 * 60 * 24,
privacy: 'public'
},
validate: {
params: {
plunkId: Joi.string().alphanum().required(),
},
query: {
d: Joi.string().required(),
},
},
handler: function (request, reply) {
var imgId = request.params.plunkId + "@" + request.query.d;
internals.cache.get(imgId)
.then(function (buf) {
reply(buf)
.etag(imgId)
.type("image/png");
}, reply);
},
},
});
server.pack.register({
plugin: require("good"),
// options: {
// subscribers: {
// 'console': [],
// '/tmp/webshot/': ['request', 'log', 'error'],
// },
// },
}, function (err) {
if (err) {
throw err; // something bad happened loading the plugin
}
server.start(function () {
server.log('info', 'Server running at: ' + server.info.uri);
});
});