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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
|
const path = require('path');
const jetpack = require('fs-jetpack');
const multer = require('multer');
const moment = require('moment');
const Util = require('../../utils/Util');
const Route = require('../../structures/Route');
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: parseInt(process.env.MAX_SIZE, 10) * (1000 * 1000),
files: 1,
},
fileFilter: (req, file, cb) =>
// TODO: Enable blacklisting of files/extensions
/*
if (options.blacklist.mimes.includes(file.mimetype)) {
return cb(new Error(`${file.mimetype} is a blacklisted filetype.`));
} else if (options.blacklist.extensions.some(ext => path.extname(file.originalname).toLowerCase() === ext)) {
return cb(new Error(`${path.extname(file.originalname).toLowerCase()} is a blacklisted extension.`));
}
*/
cb(null, true)
,
}).array('files[]');
/*
TODO: If source has transparency generate a png thumbnail, otherwise a jpg.
TODO: If source is a gif, generate a thumb of the first frame and play the gif on hover on the frontend.
TODO: Think if its worth making a folder with the user uuid in uploads/ and upload the pictures there so
that this way at least not every single file will be in 1 directory
XXX: Now that the default behaviour is to serve files with node, we can actually pull this off.
Before this, having files in subfolders meant messing with nginx and the paths,
but now it should be fairly easy to re-arrange the folder structure with express.static
I see great value in this, open to suggestions.
*/
class uploadPOST extends Route {
constructor() {
super('/upload', 'post', {
bypassAuth: true,
canApiKey: true,
});
}
async run(req, res, db) {
const user = await Util.isAuthorized(req);
if (!user && process.env.PUBLIC_MODE === 'false') return res.status(401).json({ message: 'Not authorized to use this resource' });
const albumId = req.body.albumid || req.headers.albumid;
if (albumId && !user) return res.status(401).json({ message: 'Only registered users can upload files to an album' });
if (albumId && user) {
const album = await db.table('albums').where({ id: albumId, userId: user.id }).first();
if (!album) return res.status(401).json({ message: 'Album doesn\'t exist or it doesn\'t belong to the user' });
}
return upload(req, res, async (err) => {
if (err) console.error(err.message);
let uploadedFile = {};
let insertedId;
// eslint-disable-next-line no-underscore-dangle
const remappedKeys = this._remapKeys(req.body);
const file = req.files[0];
const ext = path.extname(file.originalname);
const hash = Util.generateFileHash(file.buffer);
const filename = Util.getUniqueFilename(file.originalname);
/*
First let's get the hash of the file. This will be useful to check if the file
has already been upload by either the user or an anonymous user.
In case this is true, instead of uploading it again we retrieve the url
of the file that is already saved and thus don't store extra copies of the same file.
For this we need to wait until we have a filename so that we can delete the uploaded file.
*/
const exists = await this.checkIfFileExists(db, user, hash);
if (exists) return this.fileExists(res, exists, filename);
if (remappedKeys && remappedKeys.uuid) {
const chunkOutput = path.join(__dirname,
'../../../../',
process.env.UPLOAD_FOLDER,
'chunks',
remappedKeys.uuid,
`${remappedKeys.chunkindex.padStart(3, 0)}${ext || ''}`);
await jetpack.writeAsync(chunkOutput, file.buffer);
} else {
const output = path.join(__dirname,
'../../../../',
process.env.UPLOAD_FOLDER,
filename);
await jetpack.writeAsync(output, file.buffer);
uploadedFile = {
name: filename,
hash,
size: file.buffer.length,
url: filename,
};
}
if (!remappedKeys || !remappedKeys.uuid) {
Util.generateThumbnails(uploadedFile.name);
insertedId = await this.saveFileToDatabase(req, res, user, db, uploadedFile, file);
if (!insertedId) return res.status(500).json({ message: 'There was an error saving the file.' });
uploadedFile.deleteUrl = `${process.env.DOMAIN}/api/file/${insertedId[0]}`;
/*
If the upload had an album specified we make sure to create the relation
and update the according timestamps..
*/
this.saveFileToAlbum(db, albumId, insertedId);
}
return res.status(201).send({
message: 'Sucessfully uploaded the file.',
...uploadedFile,
});
});
}
fileExists(res, exists, filename) {
res.json({
message: 'Successfully uploaded the file.',
name: exists.name,
hash: exists.hash,
size: exists.size,
url: `${process.env.DOMAIN}/${exists.name}`,
deleteUrl: `${process.env.DOMAIN}/api/file/${exists.id}`,
repeated: true,
});
return Util.deleteFile(filename);
}
async checkIfFileExists(db, user, hash) {
const exists = await db.table('files')
.where(function () { // eslint-disable-line func-names
if (user) this.where('userId', user.id);
else this.whereNull('userId');
})
.where({ hash })
.first();
return exists;
}
async saveFileToAlbum(db, albumId, insertedId) {
if (!albumId) return;
const now = moment.utc().toDate();
try {
await db.table('albumsFiles').insert({ albumId, fileId: insertedId[0] });
await db.table('albums').where('id', albumId).update('editedAt', now);
} catch (error) {
console.error(error);
}
}
async saveFileToDatabase(req, res, user, db, file, originalFile) {
/*
Save the upload information to the database
*/
const now = moment.utc().toDate();
let insertedId = null;
try {
/*
This is so fucking dumb
*/
if (process.env.DB_CLIENT === 'sqlite3') {
insertedId = await db.table('files').insert({
userId: user ? user.id : null,
name: file.name,
original: originalFile.originalname,
type: originalFile.mimetype || '',
size: file.size,
hash: file.hash,
ip: req.ip,
createdAt: now,
editedAt: now,
});
} else {
insertedId = await db.table('files').insert({
userId: user ? user.id : null,
name: file.name,
original: originalFile.originalname,
type: originalFile.mimetype || '',
size: file.size,
hash: file.hash,
ip: req.ip,
createdAt: now,
editedAt: now,
}, 'id');
}
return insertedId;
} catch (error) {
console.error('There was an error saving the file to the database');
console.error(error);
return null;
// return res.status(500).json({ message: 'There was an error uploading the file.' });
}
}
_remapKeys(body) {
const keys = Object.keys(body);
if (keys.length) {
for (const key of keys) {
if (!/^dz/.test(key)) continue;
body[key.replace(/^dz/, '')] = body[key];
delete body[key];
}
return body;
}
return keys;
}
}
module.exports = uploadPOST;
|