Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
151 lines (133 loc) · 7 KB
/
Copy pathserver.js
File metadata and controls
151 lines (133 loc) · 7 KB
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
148
149
150
151
`
MIT License
Copyright (c) 2018 Cerulean (CeruTech)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`
const express = require('express');
const app = express();
const responseTime = require('response-time');
var cors = require('cors')
app.use(responseTime());
app.use(cors());
app.options('*', cors());
const grid = require("gridfs-stream");
const MongoClient = require('mongodb').MongoClient
const Grid = require('mongodb').GridFSBucket;
const sharp = require('sharp'); // for image optimisation
// Jasper CDN - Made by CeruTech
// can be used as a slide in replacement for any CDN url
// add "cdn_url": "http://<your-server-location>:8086" to config.json to route all
// image requests to this CDN
var db, gridFS
var supportedFormats = {
png: { 'mimetype': 'image/png' },
webp: { 'mimetype': 'image/webp' }
} // removed support for JPEG. like seriously, why do people still want JPEG?????
function reformat(data, format = 'png', quality=100) {
var transformer = sharp();
transformer = transformer.toFormat(format, { quality: quality });
return data.pipe(transformer)
}
app.get('/*', function (req, res, next) {
res.header('X-CDN-TYPE', 'Vesion 0.6 (https://github.com/AggressivelyMeows/Jasper)');
next(); // http://expressjs.com/guide.html#passing-route control
});
app.get('/api/image/:fileID', function (req, res) {
db.collection('images').findOne({ fileID: req.params.fileID }, (err, result) => {
res.set('Cache-Control', 'public, max-age=604800'); // 1 week
if (result.location == 'gridFS') {
if (req.query.format) {
if (!(req.query.format in supportedFormats)) {
res.send({ 'error': 'Format is not supported.' })
} else {
// format is supported
// convert and save to DB for future use
var format = req.query.format.toLowerCase();
var fileID = req.params.fileID + `_${format}`;
if (!format.length > 1) {
format = 'png'; //default back to png if no format detected
}
if (format == 'png') {
fileID = req.params.fileID;
}
if (!('formats' in result)) {
console.log('heck')
// object does not support formats
// try to add a polyfill
result.formats = [];
}
if (result.formats.includes(format) || format == 'png') {
// we have the file ready to go!
var readStream = gridFS.openDownloadStream(fileID);
res.set('Content-Type', supportedFormats[format].mimetype);
readStream.pipe(res);
} else {
// generate the file and send back, saving the new version in the database
var readStream = gridFS.openDownloadStream(req.params.fileID); // just get the default image
res.set('Content-Type', supportedFormats[format].mimetype);
res.set('X-Explain', `Rendered new copy of image in ${format}`);
reformat(readStream, format = req.query.format).pipe(res);
// send the file to the database now
db.collection('images').findOneAndUpdate({ fileID: req.params.fileID }, { $push: { 'formats': format, 'history': `[Jasper] Created copy of image in ${format}`} });
var writeStream = gridFS.openUploadStreamWithId(req.params.fileID + '_' + format, req.params.fileID + '_' + format );
reformat(readStream, format = req.query.format).pipe(writeStream);
}
}
} else {
// no format change, render the pure image from the database
res.set('Content-Type', 'image/png');
gridFS.openDownloadStream(req.params.fileID).pipe(res);
}
} else {
res.redirect(`https://quartz.nyc3.cdn.digitaloceanspaces.com/${result.userID}/${result.fileID}.png`);
};
});
});
app.get('/api/image/:fileID/thumbnail', function (req, res) {
var fID = req.params.fileID
db.collection('images').findOne({ fileID: fID}, (err, result) => {
res.set('Content-Type', 'image/png');
res.set('Cache-Control', 'public, max-age=604800'); // 1 week
if (result.location == 'gridFS') {
if (req.query.format) {
if (!(req.query.format in supportedFormats)) {
res.send({ 'error': 'Format is not supported.' })
} else {
// format is supported
// convert.
var readStream = gridFS.openDownloadStream(req.params.fileID + '_thumbnail');
res.set('Content-Type', supportedFormats[req.query.format].mimetype);
return reformat(readStream, format = req.query.format).pipe(res);
}
} else {
// no format change, render the pure image from the database
res.set('Content-Type', 'image/png');
gridFS.openDownloadStream(req.params.fileID + '_thumbnail').pipe(res);
}
} else {
res.redirect(`https://quartz.nyc3.cdn.digitaloceanspaces.com/${result.userID}/${fID}_thumbnail.png`);
};
})
});
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
if (err) return console.log(err);
db = client.db('quartz');
gridFS = new Grid(client.db('image_storage'));
app.listen(8086, () => {
console.log('QuartzBoard Image CDN.\nListening on port 8086.\nEnsure you have set the following inside of your config.json:\n' + JSON.stringify({ cdn_url: 'http://<your-server-location>:8086' }));
});
});