-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFilesController.js
303 lines (288 loc) · 9.3 KB
/
FilesController.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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/* eslint-disable import/no-named-as-default */
/* eslint-disable no-unused-vars */
import { tmpdir } from 'os';
import { promisify } from 'util';
import Queue from 'bull/lib/queue';
import { v4 as uuidv4 } from 'uuid';
import {
mkdir, writeFile, stat, existsSync, realpath,
} from 'fs';
import { join as joinPath } from 'path';
import { Request, Response } from 'express';
import { contentType } from 'mime-types';
import mongoDBCore from 'mongodb/lib/core';
import dbClient from '../utils/db';
import { getUserFromXToken } from '../utils/auth';
const VALID_FILE_TYPES = {
folder: 'folder',
file: 'file',
image: 'image',
};
const ROOT_FOLDER_ID = 0;
const DEFAULT_ROOT_FOLDER = 'files_manager';
const mkDirAsync = promisify(mkdir);
const writeFileAsync = promisify(writeFile);
const statAsync = promisify(stat);
const realpathAsync = promisify(realpath);
const MAX_FILES_PER_PAGE = 20;
const fileQueue = new Queue('thumbnail generation');
const NULL_ID = Buffer.alloc(24, '0').toString('utf-8');
const isValidId = (id) => {
const size = 24;
let i = 0;
const charRanges = [
[48, 57], // 0 - 9
[97, 102], // a - f
[65, 70], // A - F
];
if (typeof id !== 'string' || id.length !== size) {
return false;
}
while (i < size) {
const c = id[i];
const code = c.charCodeAt(0);
if (!charRanges.some((range) => code >= range[0] && code <= range[1])) {
return false;
}
i += 1;
}
return true;
};
export default class FilesController {
/**
* Uploads a file.
* @param {Request} req The Express request object.
* @param {Response} res The Express response object.
*/
static async postUpload(req, res) {
const { user } = req;
const name = req.body ? req.body.name : null;
const type = req.body ? req.body.type : null;
const parentId = req.body && req.body.parentId ? req.body.parentId : ROOT_FOLDER_ID;
const isPublic = req.body && req.body.isPublic ? req.body.isPublic : false;
const base64Data = req.body && req.body.data ? req.body.data : '';
if (!name) {
res.status(400).json({ error: 'Missing name' });
return;
}
if (!type || !Object.values(VALID_FILE_TYPES).includes(type)) {
res.status(400).json({ error: 'Missing type' });
return;
}
if (!req.body.data && type !== VALID_FILE_TYPES.folder) {
res.status(400).json({ error: 'Missing data' });
return;
}
if ((parentId !== ROOT_FOLDER_ID) && (parentId !== ROOT_FOLDER_ID.toString())) {
const file = await (await dbClient.filesCollection())
.findOne({
_id: new mongoDBCore.BSON.ObjectId(isValidId(parentId) ? parentId : NULL_ID),
});
if (!file) {
res.status(400).json({ error: 'Parent not found' });
return;
}
if (file.type !== VALID_FILE_TYPES.folder) {
res.status(400).json({ error: 'Parent is not a folder' });
return;
}
}
const userId = user._id.toString();
const baseDir = `${process.env.FOLDER_PATH || ''}`.trim().length > 0
? process.env.FOLDER_PATH.trim()
: joinPath(tmpdir(), DEFAULT_ROOT_FOLDER);
// default baseDir == '/tmp/files_manager'
// or (on Windows) '%USERPROFILE%/AppData/Local/Temp/files_manager';
const newFile = {
userId: new mongoDBCore.BSON.ObjectId(userId),
name,
type,
isPublic,
parentId: (parentId === ROOT_FOLDER_ID) || (parentId === ROOT_FOLDER_ID.toString())
? '0'
: new mongoDBCore.BSON.ObjectId(parentId),
};
await mkDirAsync(baseDir, { recursive: true });
if (type !== VALID_FILE_TYPES.folder) {
const localPath = joinPath(baseDir, uuidv4());
await writeFileAsync(localPath, Buffer.from(base64Data, 'base64'));
newFile.localPath = localPath;
}
const insertionInfo = await (await dbClient.filesCollection())
.insertOne(newFile);
const fileId = insertionInfo.insertedId.toString();
// start thumbnail generation worker
if (type === VALID_FILE_TYPES.image) {
const jobName = `Image thumbnail [${userId}-${fileId}]`;
fileQueue.add({ userId, fileId, name: jobName });
}
res.status(201).json({
id: fileId,
userId,
name,
type,
isPublic,
parentId: (parentId === ROOT_FOLDER_ID) || (parentId === ROOT_FOLDER_ID.toString())
? 0
: parentId,
});
}
static async getShow(req, res) {
const { user } = req;
const id = req.params ? req.params.id : NULL_ID;
const userId = user._id.toString();
const file = await (await dbClient.filesCollection())
.findOne({
_id: new mongoDBCore.BSON.ObjectId(isValidId(id) ? id : NULL_ID),
userId: new mongoDBCore.BSON.ObjectId(isValidId(userId) ? userId : NULL_ID),
});
if (!file) {
res.status(404).json({ error: 'Not found' });
return;
}
res.status(200).json({
id,
userId,
name: file.name,
type: file.type,
isPublic: file.isPublic,
parentId: file.parentId === ROOT_FOLDER_ID.toString()
? 0
: file.parentId.toString(),
});
}
/**
* Retrieves files associated with a specific user.
* @param {Request} req The Express request object.
* @param {Response} res The Express response object.
*/
static async getIndex(req, res) {
const { user } = req;
const parentId = req.query.parentId || ROOT_FOLDER_ID.toString();
const page = /\d+/.test((req.query.page || '').toString())
? Number.parseInt(req.query.page, 10)
: 0;
const filesFilter = {
userId: user._id,
parentId: parentId === ROOT_FOLDER_ID.toString()
? parentId
: new mongoDBCore.BSON.ObjectId(isValidId(parentId) ? parentId : NULL_ID),
};
const files = await (await (await dbClient.filesCollection())
.aggregate([
{ $match: filesFilter },
{ $sort: { _id: -1 } },
{ $skip: page * MAX_FILES_PER_PAGE },
{ $limit: MAX_FILES_PER_PAGE },
{
$project: {
_id: 0,
id: '$_id',
userId: '$userId',
name: '$name',
type: '$type',
isPublic: '$isPublic',
parentId: {
$cond: { if: { $eq: ['$parentId', '0'] }, then: 0, else: '$parentId' },
},
},
},
])).toArray();
res.status(200).json(files);
}
static async putPublish(req, res) {
const { user } = req;
const { id } = req.params;
const userId = user._id.toString();
const fileFilter = {
_id: new mongoDBCore.BSON.ObjectId(isValidId(id) ? id : NULL_ID),
userId: new mongoDBCore.BSON.ObjectId(isValidId(userId) ? userId : NULL_ID),
};
const file = await (await dbClient.filesCollection())
.findOne(fileFilter);
if (!file) {
res.status(404).json({ error: 'Not found' });
return;
}
await (await dbClient.filesCollection())
.updateOne(fileFilter, { $set: { isPublic: true } });
res.status(200).json({
id,
userId,
name: file.name,
type: file.type,
isPublic: true,
parentId: file.parentId === ROOT_FOLDER_ID.toString()
? 0
: file.parentId.toString(),
});
}
static async putUnpublish(req, res) {
const { user } = req;
const { id } = req.params;
const userId = user._id.toString();
const fileFilter = {
_id: new mongoDBCore.BSON.ObjectId(isValidId(id) ? id : NULL_ID),
userId: new mongoDBCore.BSON.ObjectId(isValidId(userId) ? userId : NULL_ID),
};
const file = await (await dbClient.filesCollection())
.findOne(fileFilter);
if (!file) {
res.status(404).json({ error: 'Not found' });
return;
}
await (await dbClient.filesCollection())
.updateOne(fileFilter, { $set: { isPublic: false } });
res.status(200).json({
id,
userId,
name: file.name,
type: file.type,
isPublic: false,
parentId: file.parentId === ROOT_FOLDER_ID.toString()
? 0
: file.parentId.toString(),
});
}
/**
* Retrieves the content of a file.
* @param {Request} req The Express request object.
* @param {Response} res The Express response object.
*/
static async getFile(req, res) {
const user = await getUserFromXToken(req);
const { id } = req.params;
const size = req.query.size || null;
const userId = user ? user._id.toString() : '';
const fileFilter = {
_id: new mongoDBCore.BSON.ObjectId(isValidId(id) ? id : NULL_ID),
};
const file = await (await dbClient.filesCollection())
.findOne(fileFilter);
if (!file || (!file.isPublic && (file.userId.toString() !== userId))) {
res.status(404).json({ error: 'Not found' });
return;
}
if (file.type === VALID_FILE_TYPES.folder) {
res.status(400).json({ error: 'A folder doesn\'t have content' });
return;
}
let filePath = file.localPath;
if (size) {
filePath = `${file.localPath}_${size}`;
}
if (existsSync(filePath)) {
const fileInfo = await statAsync(filePath);
if (!fileInfo.isFile()) {
res.status(404).json({ error: 'Not found' });
return;
}
} else {
res.status(404).json({ error: 'Not found' });
return;
}
const absoluteFilePath = await realpathAsync(filePath);
res.setHeader('Content-Type', contentType(file.name) || 'text/plain; charset=utf-8');
res.status(200).sendFile(absoluteFilePath);
}
}