-
Notifications
You must be signed in to change notification settings - Fork 1
/
operations.js
1002 lines (790 loc) · 29.5 KB
/
operations.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var model = require('./model.js');
var fs = require('fs');
var modm = require('modm');
var ObjectId = modm.ObjectId;
var Charset = require('jschardet');
var CSV = require('a-csv');
var mandrill = require('mandrill-api/mandrill');
var mandrill_client;
var APP_DIR = M.config.APPLICATION_ROOT + M.config.app.id;
// operations
function checkLink (link, mustHaveData) {
if (!link.params || !link.params.inboxDir) {
link.send(400, 'Missing inboxDir parameter');
return false;
}
if (mustHaveData && !link.data) {
link.send(400, 'Missing operation data');
return false;
}
if (!fs.existsSync(APP_DIR + '/' + link.params.inboxDir)) {
link.send(400, 'Inbox directory not found: ' + link.params.inboxDir);
return false;
}
return true;
}
function arrayToObjectUpdate(data, schema, mappings, key, callback) {
var obj = {};
var keyValue;
for (var fieldKey in mappings) {
if (!data[mappings[fieldKey].value]) {
continue;
}
var operator = '$set';
if (schema[fieldKey].type === 'number' && mappings[fieldKey].operator === '$inc') {
operator = '$inc';
}
if (!obj[operator]) {
obj[operator] = {};
}
if (schema[fieldKey].type === 'string') {
obj[operator][fieldKey] = data[mappings[fieldKey].value];
} else if (schema[fieldKey].type === 'number') {
obj[operator][fieldKey] = parseInt(data[mappings[fieldKey].value]);
} else if (schema[fieldKey].type === 'date') {
obj[operator][fieldKey] = new Date(data[mappings[fieldKey].value]);
} else if (schema[fieldKey].type === 'boolean') {
obj[operator][fieldKey] = Boolean(data[mappings[fieldKey].value]);
}
if (fieldKey === key) {
keyValue = obj[operator][fieldKey];
}
}
callback(obj, keyValue);
}
function insertItem (item, templateId, session, callback) {
item._tp = ObjectId(templateId);
// build request
var customRequest = {
role: session.crudRole,
session: session,
templateId: ObjectId(templateId),
data: item,
options: {},
method: 'insert'
};
M.emit('crud.create', customRequest, callback);
}
function deleteItem(query, templateId, session, callback) {
// build request
var customRequest = {
role: session.crudRole,
session: session,
templateId: ObjectId(templateId),
query: query,
options: {
justOne: true
}
};
M.emit('crud.delete', customRequest, callback);
}
function updateItem (item, keyValue, key, isUpsert, templateId, session, callback) {
item.$set._tp = ObjectId(templateId);
// build request
var query = {};
var customRequest = {
role: session.crudRole,
session: session,
templateId: ObjectId(templateId),
data: item,
options: {
upsert: isUpsert
},
method: 'update'
};
query[key] = keyValue;
customRequest.query = query;
M.emit('crud.update', customRequest, callback);
}
function arrayToObject (data, template, mappings) {
var obj = {};
for (var fieldKey in mappings) {
if (!data[mappings[fieldKey]]) {
continue;
}
var splits = fieldKey.split('.');
var curObj = obj;
var curSchema = template.schema;
for (var j = 0; j < splits.length -1; ++j) {
curObj[splits[j]] = curObj[splits[j]] || {};
curObj = curObj[splits[j]];
}
if (curSchema[fieldKey].type === 'string') {
curObj[splits[j]] = data[mappings[fieldKey]];
} else if (curSchema[fieldKey].type === 'number') {
curObj[splits[j]] = parseInt(data[mappings[fieldKey]]);
} else if (curSchema[fieldKey].type === 'date') {
curObj[splits[j]] = new Date(data[mappings[fieldKey]]);
} else if (curSchema[fieldKey].type === 'boolean') {
curObj[splits[j]] = Boolean(data[mappings[fieldKey]]);
}
}
return obj;
}
function getTemplate (templateId, role, callback) {
//build the request
var customRequest = {
role: role,
templateId: ObjectId('000000000000000000000000'),
query: {
_id: ObjectId(templateId)
},
data: {},
options: {},
method: 'read',
noCursor: true
};
//emit the request
M.emit('crud.read', customRequest, function(err, data){
if (err) {callback(err, null); return;}
callback(null, data[0]);
});
}
function sendError (link, operation, msg) {
// let the client know we had an error
M.emit('sockets.send', {
dest: link.session._sid,
type: 'session',
event: 'ie',
data: {
operation: operation,
file: link.data.path,
template: link.data.template,
status: 'error',
message: msg
}
});
}
function createList(link, callback) {
// no list for delete operations
if (link.data.operation === 'delete') {
return callback(null);
}
var createRequest = {
role: link.session.crudRole,
templateId: ObjectId('000000000000000000000004'),
data: {
_tp: [ObjectId('000000000000000000000004')],
name: 'Import ' + link.data.path,
type: 'fixed',
template: ObjectId(link.data.template)
}
};
M.emit('crud.create', createRequest, function (err, results) {
if (err || !results || !results[0]) {
return callback(err || 'Could not create import list');
}
// update the list filter with the list ID
var updateRequest = {
role: link.session.crudRole,
templateId: ObjectId('000000000000000000000004'),
query: {
_id: results[0]._id
},
data: {
$set: {
filters: [
{
field: '_li',
operator: '=',
value: results[0]._id
}
]
}
}
};
M.emit('crud.update', updateRequest, function (err, resultCount) {
if (err || !resultCount) {
return callback(err || 'Could not save import list');
}
callback(null, results[0]);
});
});
}
exports.import = function (link) {
if (!checkLink(link, true)) { return; }
// checks
if (['update', 'delete'].indexOf(link.data.operation) !== -1) {
// check if we have a key
if (!link.data.key) {
// TODO translations
return link.send(400, 'Missing operation key. Please choose a template field as key.');
}
// check if key is present in mappings
if (!link.data.mappings.hasOwnProperty(link.data.key)) {
// TODO translations
return link.send(400, 'Bad mappings. The key must be one of the mapped columns');
}
}
// create an import list
createList(link, function(err, list) {
if (err) {
link.send(400, JSON.stringify({ error: err }));
return;
}
// TODO translations
link.send(200, JSON.stringify({ success: 'Data import started' }));
// insert the data
// file path
var path = APP_DIR + '/' + link.params.inboxDir + '/' + link.data.path;
// separator
var separators = {
'COMMA': ',',
'SEMICOLON': ';',
'TAB': '\t',
'SPACE': ' '
}
var s = link.data.separator;
s = separators[s] || s;
// charset
var c = link.data.charset;
// set parse options
var options = {
// separator
delimiter: separators[link.data.separator] || link.data.separator,
// charset
charset: link.data.charset
};
// get the current template
var template;
getTemplate(link.data.template, link.session.crudRole, function(err, data) {
if (err) {
// let the client know whe had am error
sendError(link, 'import', err.toString());
return;
}
template = data;
// parse the file
var line = 0;
var itemCount = 0;
var errorCount = 0;
var firstError;
CSV.parse(path, options, function (err, row, next) {
if (err) {
// let the client know we had an error
sendError(link, 'import', err.toString());
return;
}
if (row) {
// avoid empty row
if (row.length) {
// if file contains headers skip first row
if (!link.data.headers || line > 0) {
// check if update
if (link.data.operation === 'update') {
arrayToObjectUpdate(row, template.schema, link.data.mappings, link.data.key, function(obj, keyValue) {
var object = obj;
// add the import list to this item
object.$addToSet = {};
object.$addToSet._li = list._id;
updateItem(object, keyValue, link.data.key, link.data.upsert, link.data.template, link.session, function(err) {
line++;
if (err) {
errorCount++;
if (!firstError) {
firstError = err;
}
} else {
itemCount++;
}
next();
});
});
}
else if (link.data.operation === 'insert') {
var object = arrayToObject(row, template, link.data.mappings);
// add the import list to this item
object._li = [list._id];
insertItem(object, link.data.template, link.session, function(err) {
line++;
if (err) {
errorCount++;
if (!firstError) {
firstError = err;
}
} else {
itemCount++;
}
next();
});
}
else if (link.data.operation === 'delete') {
// build delete query
var query = {};
query[link.data.key] = row[link.data.mappings[link.data.key]];
// protect against unintentional data deletion when keys are empty
if (!row[link.data.mappings[link.data.key]]) {
return next();
}
// delete item
deleteItem(query, link.data.template, link.session, function (err, data) {
line++;
if (err) {
errorCount++;
if (!firstError) {
firstError = err;
}
} else {
itemCount++;
}
next();
});
}
} else if (link.data.headers && line == 0){
line++;
next();
}
} else {
next();
}
} else {
// TODO the next function above is called one more time after the row comes nulli
// and this code will also be called twice
var result = {
dest: link.session._sid,
type: 'session',
event: 'ie',
data: {
operation: 'import',
file: link.data.path,
template: link.data.template,
count: itemCount
}
};
if (itemCount === 0 && errorCount !== 0) {
result.data.status = 'error';
result.data.errorCount = errorCount;
result.data.firstError = firstError.toString();
}
M.emit('sockets.send', result);
}
});
link.send(200, JSON.stringify({success: 'Data imported'}));
});
//TODO give an appropriate notification message when the operation is complete
});
};
exports.export = function (link) {
if (!checkLink(link, true)) { return; }
try {
var customRequest = {
role: link.session.crudRole,
templateId: ObjectId(link.data.template),
query: link.data.query,
data: {},
options: {},
method: 'read'
};
} catch (err) {
return;
}
function createTransform () {
return function (item) {
var line = '';
for (var column in link.data.columns) {
var value = findValue(item, link.data.columns[column]);
// handle date
if (value instanceof Date) {
value = value.toISOString();
} else {
value = value.toString().indexOf(link.data.separator) !== -1? '"' + value + '"' : value;
}
line += value + link.data.separator;
}
return line.slice(0, -1) + '\n';
};
}
// we can already send the response to the client
M.emit('crud.read', customRequest, function(err, resultCursor) {
if (err) {
// let the client know we had an error
sendError(link, 'export', err.toString());
return;
}
// get the file name provided, if it isn't provided make it an empty string
var filename = link.data.filename || '';
// if csv extension was provided, remove it!
// we take care about that
if (filename.substr(-4) === '.csv') {
filename = filename.substring(0, filename.lastIndexOf('.'));
}
// generate a filename like this: "export_YYYYMMDD_HHMM_original_file_name.csv"
// also, remove special characters and convert spaces in underscores
var replaces = {
'ä': 'ae', 'ú': 'u', 'î': 'i', 'ï': 'i',
'ö': 'oe', 'ó': 'o', 'ë': 'e', 'ô': 'o',
'ü': 'ue', 'ò': 'o', 'ê': 'e', 'ù': 'u',
'ß': 'ss', 'í': 'i', 'è': 'e', 'û': 'u',
'à': 'a', 'ì': 'i', 'é': 'e', 'ÿ': 'y',
'â': 'a', 'ç': 'c'
};
filename = 'export_' +
getYYYYMMDD_HHMMTime() +
'_' +
filename.replace(new RegExp('[^a-zA-Z0-9\\-\\._ ]+', 'g'), function (char) {
var result = '';
for (var i = 0; i < char.length; ++ i) {
if (replaces[char[i]]) {
result += replaces[char[i]];
}
}
return result;
}).replace(new RegExp(' ', 'g'), '_') +
'.csv';
// create the write stream
var file = fs.createWriteStream(APP_DIR + '/' + link.params.inboxDir + '/' + filename);
// write headers
if (link.data.hasHeaders) {
var headers = '';
for (var i = 0, l = link.data.columns.length; i < l; ++ i) {
headers += link.data.labels[link.data.columns[i]] + link.data.separator;
}
file.write(headers.slice(0, -1) + '\n');
}
if (resultCursor.constructor.name === 'Array') {
var transform = createTransform();
for (var i in resultCursor) {
file.write(transform(resultCursor[i]));
}
// let the client know we are done
M.emit('crud.read', {
role: link.session.crudRole,
templateId: ObjectId(link.data.template),
query: link.data.query,
data: {},
options: {},
onlyCount: true,
method: 'read'
}, function (err, count) {
if (err) {
return;
}
M.emit('sockets.send', {
dest: link.session._sid,
type: 'session',
event: 'ie',
data: {
operation: 'export',
file: filename,
template: link.data.template,
count: count
}
});
});
// send notification by email if selected
if (link.data.email && link.params.mandrillKey) {
// add the api key
mandrill_client = new mandrill.Mandrill(link.params.mandrillKey);
// build the options
var options = {
template: link.params.notificationTemplate,
to: link.session.name,
link: ''
}
// build the download link
options.link = link.req.headers.origin + '/@/import/download?path=' + filename;
// send the notification
notifyByEmail(options);
}
} else {
var stream = resultCursor.stream({ transform: createTransform() });
stream.pipe(file);
stream.on('end', function () {
// let the client know we are done
M.emit('crud.read', {
role: link.session.crudRole,
templateId: ObjectId(link.data.template),
query: link.data.query,
data: {},
options: {},
onlyCount: true,
method: 'read'
}, function (err, count) {
if (err) {
return;
}
M.emit('sockets.send', {
dest: link.session._sid,
type: 'session',
event: 'ie',
data: {
operation: 'export',
file: filename,
template: link.data.template,
count: count
}
});
});
});
// send notification by email if selected
if (link.data.email && link.params.mandrillKey) {
// add the api key
mandrill_client = new mandrill.Mandrill(link.params.mandrillKey);
// build the options
var options = {
template: link.params.notificationTemplate,
to: link.session.name,
link: ''
}
// build the download link
options.link = link.req.headers.origin + '/@/import/download?path=' + filename;
// send the notification
notifyByEmail(options);
}
}
});
};
function notifyByEmail (options) {
// build the template
var template = {
"template_name": (typeof options.template === 'object') ? options.template[M.getLocale()] : options.template,
"template_content": [],
"message": {
"to": [{
"type": "to",
"email": options.to
}],
"global_merge_vars": [{
"name": "DOWNLOAD_LINK",
"content": options.link
}]
}
};
mandrill_client.messages.sendTemplate(template, function(result) {
// check to see if rejected
if (result[0].status === 'rejected' || result[0].status === 'invalid') {
console.log(result[0].reject_reason || 'Error on sending email, check if the email provided is valid');
}
}, function(e) {
// Mandrill returns the error as an object with name and message keys
console.log('A mandrill error occurred: ' + e.name + ' - ' + e.message);
});
}
exports.readInbox = function (link) {
if (!checkLink(link)) { return; }
fs.readdir(APP_DIR + '/' + link.params.inboxDir, function(err, files) {
var inboxFiles = [];
for (var i in files) {
// do not return hidden files
if (files[i][0] === '.') {
continue;
}
inboxFiles.push({ path: files[i] });
}
// sort the files in reverse order
inboxFiles.sort(function(a, b) {
if (a.path > b.path) return -1;
if (a.path < b.path) return 1;
return 0;
});
link.send(200, inboxFiles);
});
};
exports.deleteFile = function (link) {
if (!checkLink(link, true)) { return; }
var path = link.data;
if (!path) { return; }
//process path
var modifiedPath = path.replace(/\.\.\//g, '');
modifiedPath = modifiedPath.replace(/\.\//g, '');
fs.unlink(APP_DIR + '/' + link.params.inboxDir + '/' + modifiedPath, function (err) {
if (err) {
link.send(400, 'Bad Request');
return;
}
});
link.send(200, 'ok');
};
exports.download = function (link) {
// prevent bad requests
if (!link.data && !link.query) { return link.send(400, 'Bad Request'); }
if (!checkLink(link, false)) { return; }
// get the path of the file
var filePath;
if (link.data && link.data.path) {
filePath = link.data.path;
} else if (link.query && link.query.path) {
filePath = link.query.path;
} else {
return link.send(400, 'Missing file path');
}
// check if the file path was added correctly
if (!filePath) { return link.send(500); }
var path = APP_DIR + '/' + link.params.inboxDir + '/' + filePath;
if(!path) { return link.send(500); }
// check if the file exists
fs.exists(path, function (exists) {
if (!exists) { return link.send(404, '404 File not found'); }
// build the headers
link.res.writeHead(200, {
'Content-disposition': 'attachment;filename="' + filePath + '"',
'Content-Type': 'text/csv'
});
var filestream = fs.createReadStream(path);
filestream.pipe(link.res);
});
};
exports.getColumns = function (link) {
if (!checkLink(link, true)) { return; }
// the file path from inbox directory
var path = APP_DIR + '/' + link.params.inboxDir + '/' + link.data.path;
// separators
var separators = {
'COMMA' : ',',
'SEMICOLON' : ';',
'TAB' : '\t',
'SPACE' : ' '
};
// create the read stream
var readStream = fs.createReadStream(path);
// initialize first line as empty string
var firstLine = '';
// on data
var data = '';
readStream.on('data', function (chunk) {
// add chunk to firstLine
data += chunk;
// split the file at new line to get the first line
var lines = data.split('\n');
// check if the first line exists
if (lines[0].length) {
// get the first line
firstLine = lines[0];
// end stream
readStream.close();
// start parsing the file
// how many lines?
var l = parseInt(link.data.lineCount) || 10;
// separator
var s = link.data.separator || getCSVSeparator(firstLine)[0];
s = separators[s] || s;
// charset
var c = link.data.charset || Charset.detect(firstLine).encoding;
// force hasHeaders to be boolean
link.data.hasHeaders = link.data.hasHeaders ? true : false;
// set parse options
var options = {
delimiter: s,
charset: c
};
var i = 0;
var lines = [];
var headers;
// parse the file
CSV.parse(path, options, function (err, row, next) {
// handle error
if (err) { return link.send(400, err); }
// push line or set headers
if (link.data.hasHeaders && i === 0) {
headers = row;
}
// row exits, push it
else if (row && row.length) {
lines.push(row);
// row is null, that means that we've read the entire file
} else {
l = i;
}
// go to next line
if (++i < l) {
next();
}
else {
// set mappings obj
var mappings = {
// the read lines
lines: lines,
// separator
separator: s,
// charset
charset: c,
// how many lines
lineCount: l,
// the headers (an array or undefined)
headers: headers,
// hasHeaders: boolean
hasHeaders: link.data.hasHeaders
};
// send response
link.send(200, mappings);
}
});
} else {
return link.send(400, 'Empty file');
}
});
// handle errors
readStream.on('error', function (err) {
return link.send(400, err);
});
};
// private functions
function findValue (parent, dotNot) {
if (!dotNot) return undefined;
var splits = dotNot.split('.');
var value;
for (var i = 0; i < splits.length; i++) {
value = parent[splits[i]];
if (value === undefined || value === null) return '';
if (typeof value === 'object') parent = value;
}
return value;
}
// get csv separator
// TODO Handle quoted fields
function getCSVSeparator (text) {
var possibleDelimiters = [';', ',', '\t'];
return possibleDelimiters.filter(weedOut);
function weedOut (delimiter) {
var cache = -1;
return text.split('\n').every(checkLength);
function checkLength (line) {
if (!line) {
return true;
}
var length = line.split(delimiter).length;
if (cache < 0) {
cache = length;
}
return cache === length && length > 1;
}
}
}
// internal functions
function getUpload(link, callback) {
var ds = 'dsUpload';
if (!link.params || !link.params[ds]) {
return callback('Missing datasource operations parameter: ' + ds);
}
if (!link.data || !link.data.upload) {
return callback('Missing upload id');
}
M.datasource.resolve(link.params[ds], function(err, ds) {
if (err) { return callback(err); }
M.database.open(ds, function(err, db) {
if (err) { return callback(err); }
db.collection(ds.collection, function(err, collection) {
if (err) { return callback(err); }
collection.findOne({ _id: new ObjectId(link.data.upload) }, function(err, upload) {
if (err || !upload) { return callback(err || 'No such upload: ' + link.data.upload); }
callback(null, upload);
});
});
});
});
}
function getYYYYMMDD_HHMMTime() {
var date = new Date();
var hour = date.getHours();
hour = ((hour < 10 ? '0' : '') + hour).toString();
var min = date.getMinutes();
min = ((min < 10 ? '0' : '') + min).toString();
var sec = date.getSeconds();
sec = ((sec < 10 ? '0' : '') + sec).toString();
var year = date.getFullYear().toString();
var month = date.getMonth() + 1;
month = ((month < 10 ? '0' : '') + month).toString();
var day = date.getDate();
day = ((day < 10 ? '0' : '') + day).toString();
return year + month + day + '_' + hour + min;