-
Notifications
You must be signed in to change notification settings - Fork 0
/
dump_content.js
108 lines (79 loc) · 2.45 KB
/
dump_content.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
#!/usr/bin/env node
/**
* run this node script in order to add images to our mongodb
* this simulates what wetopi api does when user posts an image.
*/
var config = require('./config');
var fs = require('fs');
var mime = require('mime');
var crypto = require('crypto');
var uuid = require('node-uuid');
var db = require('./lib/db');
var message = require('./lib/message');
var imgData = require('./lib/img_data');
var debug = require('debug')('dump_content');
var VError = require('verror');
debug('start');
// do not start until we have a connection to share on every file management
db.getMongoDbConnection(function() {
// Fs input dir where test images come from
if(!fs.existsSync(config.in_path)) fs.mkdirSync(config.in_path, 0777);
addAllFilesFromFs();
debug('done');
});
/**
* Read files from fs, saves them to db and emmits a message for each one when done.
*/
function addAllFilesFromFs() {
var dir = config.in_path;
var files = fs.readdirSync(dir);
files.forEach(function(fileName) {
var theFile = dir + '/' + fileName;
if (fs.statSync(theFile).isFile()) {
addThisFile(theFile, function(err, data) {
if (err) {
console.error(err.message);
} else {
message.publish(config.upload, data);
}
});
}
});
}
/**
* Given a local fs stored image file, store it to GridFS
* @param theFile the filename with its path
* @param callback a required function
*
* the data passed to callback is an image object as def in img_data
*/
function addThisFile(theFile, callback) {
var mimeType = mime.lookup(theFile);
var fileName = generateNewFileName();
var err = false;
if (!validImageType(mimeType)) {
// fs.unlink(theFile);
err = new VError('Image type for %s not supported. Try uploading JPG or PNG images.', theFile);
console.error(err.message);
return callback(err);
}
db.storeFile(theFile, fileName, mimeType, function (err) {
var data = imgData.make({
filename: fileName,
mime: mimeType
});
if (err) {
err = new VError(err, 'Error trying to store %s with id %s', theFile, fileName);
console.error(err.message);
return callback(err);
}
// fs.unlink(theFile);
callback(err, data);
});
}
function generateNewFileName() {
return crypto.createHash('md5').update(uuid.v4()).digest("hex");
}
function validImageType(mimeType) {
return ["image/gif", "image/jpeg", "image/png"].indexOf(mimeType) !== -1;
}