aboutsummaryrefslogtreecommitdiff
path: root/src/api/routes/uploads/chunksPOST.js
blob: 1c02bc704e45580cf41b431998c4f7a531eda035 (plain) (blame)
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
const Route = require('../../structures/Route');
const path = require('path');
const Util = require('../../utils/Util');
const jetpack = require('fs-jetpack');
const randomstring = require('randomstring');

class uploadPOST extends Route {
	constructor() {
		super('/upload/chunks', 'post', { bypassAuth: true });
	}

	async run(req, res, db) {
		const filename = Util.getUniqueFilename(randomstring.generate(32));
		// console.log('Files', req.body.files);
		const info = {
			size: req.body.files[0].size,
			url: `${process.env.DOMAIN}/`
		};

		for (const chunk of req.body.files) {
			const { uuid, count } = chunk;
			// console.log('Chunk', chunk);

			const chunkOutput = path.join(__dirname,
				'..',
				'..',
				'..',
				'..',
				process.env.UPLOAD_FOLDER,
				'chunks',
				uuid);
			const chunkDir = await jetpack.list(chunkOutput);
			const ext = path.extname(chunkDir[0]);
			const output = path.join(__dirname,
				'..',
				'..',
				'..',
				'..',
				process.env.UPLOAD_FOLDER,
				`${filename}${ext || ''}`);
			chunkDir.sort();

			// Save some data
			info.name = `${filename}${ext || ''}`;
			info.url += `${filename}${ext || ''}`;

			for (let i = 0; i < chunkDir.length; i++) {
				const dir = path.join(__dirname,
					'..',
					'..',
					'..',
					'..',
					process.env.UPLOAD_FOLDER,
					'chunks',
					uuid,
					chunkDir[i]);
				const file = await jetpack.readAsync(dir, 'buffer');
				await jetpack.appendAsync(output, file);
			}
			await jetpack.removeAsync(chunkOutput);
		}

		return res.status(201).send({
			message: 'Sucessfully merged the chunk(s).',
			...info
			/*
			name: `${filename}${ext || ''}`,
			size: exists.size,
			url: `${process.env.DOMAIN}/${exists.name}`,
			deleteUrl: `${process.env.DOMAIN}/api/file/${exists.id}`
			*/
		});
	}
}

module.exports = uploadPOST;