-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrouter.js
392 lines (348 loc) · 11.4 KB
/
router.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
const path = require('path'),
fs = require('fs-extra'),
formidable = require('formidable'),
archiver = require('archiver');
const sockets = require('./core/sockets'),
dev = require('./core/dev-log'),
cache = require('./core/cache'),
api = require('./core/api'),
file = require('./core/file'),
exporter = require('./core/exporter');
module.exports = function(app, io, m) {
/**
* routing event
*/
app.get('/', showIndex);
app.get('/:folder', loadFolderOrMedia);
app.get('/:folder/media/:metaFileName', loadFolderOrMedia);
app.get('/publication/:publication', printPublication);
app.get('/publication/web/:publication', exportPublication);
app.get('/publication/print/:pdfName', showPDF);
app.get('/publication/video/:videoName', showVideo);
app.post('/:folder/file-upload', postFile2);
/**
* routing functions
*/
function generatePageData(req) {
return new Promise(function(resolve, reject) {
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
dev.log(`••• the following page has been requested: ${fullUrl} •••`);
let pageData = {};
pageData.pageTitle = 'millefeuille';
// full path on the storage space, as displayed in the footer
pageData.folderPath = api.getFolderPath();
pageData.slugFolderName = '';
pageData.url = req.path;
pageData.protocol = req.protocol;
pageData.folderPreviewFilename_ext =
global.settings.folderPreviewFilename + global.settings.thumbExt;
pageData.structure = global.settings.structure;
// pageData.authorsFolder = global.settings.structure.authors.path;
pageData.isDebug = dev.isDebug();
if (global.hasOwnProperty('mode')) {
pageData.mode = global.mode;
} else {
pageData.mode = 'live';
}
resolve(pageData);
});
}
// GET
function showIndex(req, res) {
generatePageData(req).then(
pageData => {
dev.logpackets(
`Rendering index with data `,
JSON.stringify(pageData, null, 4)
);
if (pageData.mode !== 'read_only') {
res.render('index', pageData);
} else {
if (global.hasOwnProperty('foldersAndMediaData')) {
pageData.foldersAndMediaData = global.foldersAndMediaData;
res.render('index', pageData);
} else {
const type = 'layers';
file.getFolder({ type }).then(foldersData => {
let tasks = [];
Object.keys(foldersData).map(slugFolderName => {
let myPromise = new Promise((resolve, reject) => {
exporter
.getFolderAndMedia({ slugFolderName, type })
.then(d => {
resolve(d);
});
});
tasks.push(myPromise);
});
Promise.all(tasks).then(d_array => {
let allLayersAndMedias = {};
d_array.map(d => {
const k = Object.keys(d)[0];
const v = Object.values(d)[0];
allLayersAndMedias[k] = v;
});
global.foldersAndMediaData = allLayersAndMedias;
pageData.foldersAndMediaData = global.foldersAndMediaData;
res.render('index', pageData);
});
});
}
}
},
err => {
dev.error(`Err while getting index data: ${err}`);
}
);
}
function loadFolderOrMedia(req, res) {
let slugFolderName = req.param('folder');
let metaFileName = req.param('metaFileName');
generatePageData(req).then(
pageData => {
// let’s make sure that folder exists first and return some meta
file
.getFolder({ type: 'layers', slugFolderName })
.then(
foldersData => {
pageData.slugFolderName = slugFolderName;
pageData.folderAndMediaData = foldersData;
if (metaFileName) {
pageData.metaFileName = metaFileName;
}
res.render('index', pageData);
},
(err, p) => {
dev.error(`Failed to get folder: ${err}`);
pageData.noticeOfError = 'failed_to_find_folder';
res.render('index', pageData);
}
)
.catch(err => {
dev.error('No folder found');
});
},
err => {
dev.error(`Err while getting index data: ${err}`);
}
);
}
function printPublication(req, res) {
let slugPubliName = req.param('publication');
generatePageData(req).then(pageData => {
exporter.loadPublication(slugPubliName, pageData).then(pageData => {
pageData.mode = 'print_publication';
res.render('index', pageData);
});
});
}
function exportPublication(req, res) {
let slugPubliName = req.param('publication');
generatePageData(req).then(pageData => {
exporter.loadPublication(slugPubliName, pageData).then(pageData => {
pageData.mode = 'export_publication';
res.render('index', pageData, (err, html) => {
exporter
.copyPubliContent({
html,
folders_and_medias: pageData.folderAndMediaData,
slugPubliName
})
.then(
cachePath => {
var archive = archiver('zip');
archive.on('error', function(err) {
res.status(500).send({ error: err.message });
});
//on stream closed we can end the request
archive.on('end', function() {
dev.log('Archive wrote %d bytes', archive.pointer());
});
//set the archive name
res.attachment(slugPubliName + '.zip');
//this is the streaming magic
archive.pipe(res);
archive.directory(cachePath, false);
archive.finalize();
},
(err, p) => {
dev.error('Failed while preparing/making a web export');
}
);
});
});
});
}
function showPDF(req, res) {
let pdfName = req.param('pdfName');
const cachePath = path.join(
global.tempStorage,
global.settings.cacheDirname,
'_publications'
);
const pdfPath = path.join(cachePath, pdfName);
res.download(pdfPath, pdfName, function(err) {
if (err) {
} else {
}
});
}
function showVideo(req, res) {
let videoName = req.param('videoName');
const cachePath = path.join(
global.tempStorage,
global.settings.cacheDirname,
'_publications'
);
const videoPath = path.join(cachePath, videoName);
res.download(videoPath, videoName, function(err) {
if (err) {
} else {
}
});
}
function postFile2(req, res) {
let slugFolderName = req.param('folder');
dev.logverbose(`Will add new media for folder ${slugFolderName}`);
// create an incoming form object
var form = new formidable.IncomingForm();
// specify that we want to allow the user to upload multiple files in a single request
form.multiples = false;
form.maxFileSize = 1000 * 1024 * 1024;
let socketid = '';
// store all uploads in the folder directory
form.uploadDir = api.getFolderPath(slugFolderName);
let allFilesMeta = [];
let fieldValues = {};
form.on('field', function(name, value) {
console.log(`Got field with name = ${name} and value = ${value}.`);
if (name === 'socketid') {
socketid = value;
}
try {
fieldValues[name] = JSON.parse(value);
} catch (e) {
// didn’t get an object as additional meta
}
});
// every time a file has been uploaded successfully,
form.on('file', function(field, uploadedFile) {
dev.logverbose(
`File uploaded:\nfield: ${field}\nfile: ${JSON.stringify(
uploadedFile,
null,
4
)}.`
);
// add addiontal meta from 'field' to the array
let newFile = uploadedFile;
for (let fileName in fieldValues) {
if (fileName === newFile.name) {
newFile = Object.assign({}, newFile, {
additionalMeta: fieldValues[fileName]
});
}
}
// dev.logverbose(`Found matching filenames, new meta file is: ${JSON.stringify(newFile,null,4)}`);
allFilesMeta.push(newFile);
});
// log any errors that occur
form.on('error', function(err) {
console.log(`An error has happened: ${err}`);
});
form.on('aborted', function(err) {
console.log(`File upload aborted: ${err}`);
});
// once all the files have been uploaded
form.on('end', function() {
console.log(`All files have been sent`);
let msg = {};
msg.msg = 'success';
// msg.medias = JSON.stringify(allFilesMeta);
res.end(JSON.stringify(msg));
if (allFilesMeta.length > 0) {
var m = [];
for (var i in allFilesMeta) {
m.push(
renameAndConvertMediaAndCreateMeta(
form.uploadDir,
slugFolderName,
allFilesMeta[i],
socketid
)
);
}
Promise.all(m).then(() => {});
} else {
var m = [];
for (var n in fieldValues) {
m.push(
sockets.createMediaMeta({
type: 'layers',
slugFolderName: slugFolderName,
additionalMeta: fieldValues[n]
})
);
}
Promise.all(m).then(() => {});
}
});
// parse the incoming request containing the form data
form.parse(req);
}
function renameAndConvertMediaAndCreateMeta(
uploadDir,
slugFolderName,
fileMeta,
socketid
) {
return new Promise(function(resolve, reject) {
dev.logfunction('ROUTER — renameAndConvertMediaAndCreateMeta');
api.findFirstFilenameNotTaken(uploadDir, fileMeta.name).then(
function(newFileName) {
dev.logverbose(`Following filename is available: ${newFileName}`);
if (fileMeta.hasOwnProperty('additionalMeta')) {
dev.logverbose(
`Has additional meta: ${JSON.stringify(
fileMeta.additionalMeta,
null,
4
)}`
);
} else {
fileMeta.additionalMeta = {};
}
file
.convertAndSaveMedia({
uploadDir,
tempPath: fileMeta.path,
newFileName,
socketid
})
.then(newFileName => {
fileMeta.additionalMeta.media_filename = newFileName;
sockets.createMediaMeta({
type: 'layers',
slugFolderName: slugFolderName,
additionalMeta: fileMeta.additionalMeta
});
resolve();
})
.catch(err => {
dev.error(err);
fileMeta.additionalMeta.media_filename = newFileName;
sockets.createMediaMeta({
type: 'layers',
slugFolderName: slugFolderName,
additionalMeta: fileMeta.additionalMeta
});
resolve();
});
},
function(err) {
reject(err);
}
);
});
}
};