-
Notifications
You must be signed in to change notification settings - Fork 0
/
gallery.js
187 lines (166 loc) · 6.22 KB
/
gallery.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
const fs = require('fs-extra');
const path = require('path');
const jimp = require('jimp');
const multer = require('multer');
const mUpload = multer({
storage: multer.memoryStorage(),
fileFilter(req, file, next) {
const isPhoto = file.mimetype.startsWith('image/');
if (isPhoto) {
next(null, true);
} else {
next({ message: "That filetype isn't allowed!" }, false);
}
},
});
const publicRootDir = path.join(process.mainModule.paths[0].split('node_modules')[0].slice(0, -1), 'public'); // Thank you pddivine: Finds root of express app.
exports = module.exports = createGallery;
//* ***********************************************************************//
function createGallery(options = {}) {
const defaultOptions = {
galleryRoot: path.join(publicRootDir, 'images', 'gallery'),
galleryPublicRoot: path.join('images', 'gallery'),
category: 'category',
imageFileSelectField: 'images',
imageWidth: null,
thumbNailWidth: 250,
};
for (const opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) {
options[opt] = defaultOptions[opt];
}
}
return {
upload,
getIndex,
getImagesFromCategory,
removeCategory,
removeImage,
};
//* ***********************************************************************//
function upload() { // TODO add options like using as middleware
return function uploadImages(req, res, next) {
mUpload.array(options.imageFileSelectField)(req, res, () => {
Promise.all(req.files.map(image => Promise.all([
saveImage(image, req.body[options.category]), // TODO set category
saveThumbnail(image, req.body[options.category]),
])))
.then(() => { res.status(200).send('Successful Upload'); })
.catch((err) => { res.status(500).send(err); });
});
};
}
function getIndex(funcOptions = {}) {
return function getGalleryIndex(req, res, next) {
getCategories(options.galleryRoot)
.then(generateCategoryCards)
.then((cards) => {
req.gallery = cards;
if (funcOptions.ajax) return res.status(200).send(cards);
return next();
})
.catch((err) => {
if (!funcOptions.ajax) return res.status(500).send(err);
return next(err);
});
};
}
function getImagesFromCategory(funcOptions = {}) {
return function getImages(req, res, next) { // TODO - allow passing of arguments for category
generateImageCards(req.params.category)
.then((imageCards) => {
if (funcOptions.ajax) { return res.status(200).json(imageCards); }
req.gallery = imageCards;
return next();
})
.catch((err) => {
if (funcOptions.ajax) return res.status(404).send('Category Not Found');
return next(err);
});
};
}
function removeCategory(funcOptions) {
return function deleteCategoryDir(req, res, next) { // TODO check for windows compatibility
fs.remove(path.join(options.galleryRoot, req.params.category))
.then(() => {
if (funcOptions.ajax) return res.status(204).send('');
return next();
})
.catch((err) => {
if (funcOptions.ajax) return res.status(400).send('');
return next(err);
});
}
}
function removeImage(funcOptions) { // TODO allow setting as middleware, dynamic params
return function removeImage(req, res, next) {
const category = req.params.category;
const image = req.params.image;
fs.unlink(path.join(options.galleryRoot, category, image))
.then(() => {
fs.unlink(path.join(options.galleryRoot, category, 'thumbnails', `_${image}`));
})
.then(() => {
res.status(202).send('');
})
.catch(err => res.status(400).send(err));
};
}
function saveImage(file, category) { // TODO allow renaming from form field
return jimp.read(file.buffer)
.then((image) => {
if (options.imageWidth) { image.resize(options.imageWidth, jimp.AUTO); }
image.write(path.join(options.galleryRoot, category, file.originalname));
})
.catch(console.error);
}
function saveThumbnail(file, category) { // TODO allow renaming from form field
return jimp.read(file.buffer)
.then((image) => {
image.resize(options.thumbNailWidth, jimp.AUTO);
image.write(path.join(options.galleryRoot, category, 'thumbnails', `_${file.originalname}`));
console.log(path.join(options.galleryRoot, category, 'thumbnails', `_${file.originalname}`));
})
.catch(console.error);
}
function getCategories(directory) { // TODO - do not show empty categories and/or remove them
return new Promise((resolve, reject) => {
fs.readdir(directory, (err, categories) => {
if (err) reject(err);
resolve(categories);
});
});
}
function generateCategoryCards(categories) {
return Promise.all(categories.map(category => getCategoryThumbnails(category)
.then(thumbnails => ({
category,
thumbnail: thumbnails[0],
}))
.catch(err => err)));
}
function getCategoryThumbnails(category) { // TODO IF no thumbnail directory, use puctures
return new Promise((resolve, reject) => {
fs.readdir(path.join(options.galleryRoot, category, 'thumbnails'), (err, contents) => {
if (err) reject(err);
if (contents == null) { return reject('noThumb'); }
resolve(contents.map(thumbnail => path.join(options.galleryPublicRoot, category, 'thumbnails', thumbnail)));
});
});
}
function generateImageCards(category) {
return new Promise((resolve, reject) => {
fs.readdir(path.join(options.galleryRoot, category), (err, contents) => {
if (err) reject(err);
if (contents == null) return reject();
const images = contents.filter(file => file !== 'thumbnails');
resolve(images.map(image => ({
imageName: path.parse(image).name, // Thank you: Alex Chuev
imageURL: `/${options.galleryPublicRoot}/${category}/${image}`,
thumbURL: `/${options.galleryPublicRoot}/${category}/thumbnails/_${image}`,
imageExt: path.parse(image).ext,
})));
});
});
}
}