forked from cianclarke/node-gallery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gallery.js
446 lines (401 loc) · 14.9 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
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
var fs = require('fs'),
exif = require('./picutil.js'),
walk = require('walk'),
path = require('path'),
util = require('util');
var gallery = {
/*
* Directory where the photos are contained
*/
directory: undefined,
/*
* Optional static directory to prefix our directory references with
* This won't get output in templates - only needed if we've defined a static
* directory in a framework like express.
*/
static: undefined,
/*
* root URL of the gallery - defaults to root, or '' - NOT '/'
* an example would be '/gallery', NOT '/gallery/'
* This has no reflection on where the static assets are stored
* it's just where our gallery lies in a URL router
*/
rootURL: '',
/*
* Our constructed album JSON lives here
*/
album: undefined,
/*
* Name of our gallery
*/
name: 'My Gallery',
/*
* Image to display when no thumbnail could be located
*/
noThumbnail: '', // TODO: Bundle a default no thumbnail image?
/*
* Filter string to use for excluding filenames. Defaults to a regular expression that excludes dotfiles.
*/
//ignore _thumb_*
filter: /^Thumbs.db|^_thumb_*|^\.[a-zA-Z0-9]+/,
/*
* Private function to walk a directory and return an array of files
*/
readFiles: function (params, cb) {
var files = [],
directoryPath = this.directory,
me = this;
directoryPath = path.resolve(this.static, this.directory);
console.log("reading directory: " + directoryPath);
var walker = walk.walk(directoryPath, {
followLinks: false
});
//TODO:
walker.on("directories", function (root, dirStatsArray, next) {
//Can be comment out.
next();
});
walker.on('file', function (root, stat, next) {
if (stat.name.match(me.filter) != null) {
return next();
}
var file = {
type: stat.type,
name: stat.name,
dir: root.replace(directoryPath, ""),
};
files.push(file);
return next();
});
walker.on('end', function () {
return cb(null, files);
});
},
/*
* Private function to build an albums object from the files[] array
*/
buildAlbums: function (files, cb) {
var albums = {
name: this.name,
prettyName: this.name,
photos: [],
path: "",
hash: "",
isRoot: true,
albums: []
},
dirHash = {};
for (var i = 0; i < files.length; i++) {
// Process a single file
console.log("Building File : " + files[i].dir + path.sep + files[i].name);
var file = files[i],
dirs = file.dir.split(path.sep),
dirHashKey = "",
pAlbum = albums,
curAlbum = albums; // reset current album to root at each new file
var curDir = dirs.slice(-1)[0];
var pdirHashKey = dirs.slice(0, dirs.length - 1);
pdirHashKey = pdirHashKey.join("");
dirHashKey = dirs.join("");
pAlbum = searchAlbum(albums, pdirHashKey);
if (!pAlbum) pAlbum = albums;
if (curDir == "") {
//Root Directory, beacomes the TOP level album.
curDir = "/";
dirHash[""] = "";
};
if (!dirHash.hasOwnProperty(dirHashKey)) {
console.log("coming to create dir hash " + dirHashKey);
// If we've never seen this album before, let's create it
var currentAlbumPath = dirs.join(path.sep);
dirHash[dirHashKey] = true // TODO - consider binding the album to this hash, and even REDIS-ing..
var newAlbum = {
name: curDir,
prettyName: decodeURIComponent(curDir),
description: "",
hash: dirHashKey,
path: currentAlbumPath,
photos: [],
albums: []
};
pAlbum.albums.push(newAlbum);
curAlbum = newAlbum;
} else {
// we've seen this album, we need to drill into it
// search for the right album & update curAlbum
var curAls = pAlbum.albums;
for (var k = 0; k < curAls.length; k++) {
var al = curAls[k];
if (al.hash === dirHashKey) {
curAlbum = al;
break;
}
}
}
var fullpath = path.join(this.static, this.directory, file.dir, file.name);
if (file.name == "info.json") {
var info = fs.readFileSync(fullpath);
try {
info = JSON.parse(info);
} catch (e) {
// If invalid JSON, just bail..
continue;
}
curAlbum.description = info.description || null;
curAlbum.prettyName = info.name || curAlbum.prettyName;
if (info.thumb || info.thumbnail) {
var thumbnailImage = info.thumb || info.thumbnail;
thumbnailImage = curAlbum.path + "/" + thumbnailImage;
curAlbum.thumb = thumbnailImage;
}
} else {
//remove ext
var photoName = file.name.replace(/.[^\.]+$/, "");
var photo = {
name: photoName,
//path: fullpath.replace(this.directory,"").replace(this.static,"")
path: path.join(file.dir, file.name)
};
// sample:
// { name: '390_G', path: 'Ireland/West Coast/390_G.jpg' }
var myself = this;
// we have a photo object - let's try get it's exif data. We've
// already pushed into curAlbum, no rush getting exif now!
// Create a closure to give us scope to photo
(function (photo, curAlbum) {
var fullPath = path.join(myself.static, myself.directory, photo.path);
exif.exif(fullPath, photo, function (err, exifPhoto) {
// no need to do anything with our result - we've altered
// the photo object..
//console.log(exifPhoto);
});
exif.imConvert(fullPath, photo, function (err, out) {
var photopath = photo.path;
photo.thumb = path.dirname(photopath) + path.sep + path.basename(photo.thumb);
//console.log(out);
});
})(photo, curAlbum);
curAlbum.photos.push(photo);
}
}
//console.log(JSON.stringify(pAlbum,null,2));
//console.log(JSON.stringify(albums,null,2));
// Function to iterate over our completed albums, calling _buildThumbnails on each
function _recurseOverAlbums(al) {
if (!al.thumb) {
al.thumb = _buildThumbnails(al); // only set this album's thumbanil if not already done in info.json
}
if (al.albums.length > 0) {
for (var i = 0; i < al.albums.length; i++) {
_recurseOverAlbums(al.albums[i]);
}
}
}
var me = this;
function _buildThumbnails(album) {
var photoChildren = album.photos,
albumChildren = album.albums;
if (photoChildren.length && photoChildren.length > 0) {
var albumThumb = photoChildren[0].path;
return albumThumb;
} else {
if (albumChildren.length && albumChildren.length > 1) {
return _buildThumbnails(albumChildren[0]);
} else {
// TODO: No image could be found
return me.noThumbnail;
}
}
}
_recurseOverAlbums(albums);
return cb(null, albums);
},
/*
* Public API to node-gallery, currently just returns JSON block
*/
init: function (params, cb) {
var me = this,
directory = params.directory;
if (!cb || typeof cb !== "function") {
cb = function (err) {
if (err) {
throw new Error(err.toString());
}
};
}
if (!directory) throw new Error('`directory` is a required parameter');
// Massage our static directory and directory params into our expected format
// might be easier by regex..
console.log("directory " + directory);
this.rootURL = params.rootURL;
this.directory = directory;
this.static = params.static;
console.log("static" + this.static);
this.name = params.name || this.name;
this.filter = params.filter || this.filter;
this.readFiles(null, function (err, files) {
if (err) {
console.log("ERR" + err);
return cb(err);
}
me.buildAlbums(files, function (err, album) {
me.album = album;
return cb(err, album);
})
});
},
/*
* Returns a photo. Usage:
* getPhoto({ photo: 'test.jpg', album: 'Ireland'}, function(err, photo){
* console.log(photo.path);
* );
*/
getPhoto: function (params, cb) {
// bind the album name to the request
var photoName = params.photo.replace(/.[^\.]+$/, ""), // strip the extension
albumPath = params.album;
this.getAlbum(params, function (err, data) {
if (err) {
return cb(err);
};
var album = data.album;
var photos = album.photos;
for (var i = 0; i < photos.length; i++) {
var photo = photos[i];
if (photo.name === photoName) {
return gallery.afterGettingItem(null, {
type: 'photo',
photo: photo
}, cb);
}
}
return cb('Failed to load photo ' + photoName + ' in album ' + albumPath, null);
});
},
/*
* Function to return a specific album. Usage:
* gallery.getAlbum({ album: 'Ireland/Waterford', function(err, album){
* console.log(album.path);
* });
*/
getAlbum: function (params, cb) {
var album = this.album,
albumPath = params.album;
console.log("album " + albumPath);
//console.log(JSON.stringify(album,null,2));
if (!albumPath || albumPath == '') {
//return cb(null, album);
return this.afterGettingItem(null, {
type: 'album',
album: album
}, cb);
}
var dirs = albumPath.split(path.sep);
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
var aChildren = album.albums;
for (var j = 0; j < aChildren.length; j++) {
var aChild = aChildren[j];
if (aChild.name === dir) {
album = aChild;
}
}
}
if (album.hash !== dirs.join("")) {
console.log(dirs.join(""));
return cb('Failed to load album ' + albumPath, null);
}
return this.afterGettingItem(null, {
type: 'album',
album: album
}, cb);
},
/*
* Private function which massages the return type into something useful to a website.
* Builds stuff like a breadcrumb, back URL..
*/
afterGettingItem: function (err, data, cb) {
var item = data[data.type];
var breadcrumb = item.path.split("/");
var back = data.back = breadcrumb.slice(0, item.path.split("/").length - 1).join("/"); // figure out up a level's URL
// Construct the breadcrumb better.
data.breadcrumb = [];
var breadSoFar = "" + this.rootURL + "";
// Add a root level to the breadcrumb
data.breadcrumb.push({
name: this.name,
url: this.rootURL
});
for (var i = 0; i < breadcrumb.length; i++) {
var b = breadcrumb[i];
if (b == "") {
continue;
}
breadSoFar += "/" + breadcrumb[i];
data.breadcrumb.push({
name: b,
url: breadSoFar
});
}
data.name = this.name;
data.directory = this.directory;
data.rootDir = this.rootURL;
return cb(err, data);
},
middleware: function (options) {
var me = this;
this.init(options);
return function (req, res, next) {
var url = req.url,
rootURL = gallery.rootURL,
params = req.params,
requestParams = {},
image = false;
var staticTest = /\.png|\.jpg|\.css|\.js/i;
if (rootURL == "" || url.indexOf(rootURL) === -1 /*|| staticTest.test(url)*/) {
return next();
}
url = url.replace(rootURL, "");
// Do some URL massaging - wouldn't have to do this if .params were accessible?
if (url.charAt(0) === "/") {
url = url.substring(1, url.length);
}
url = decodeURIComponent(url);
if (url && url !== "") {
var path = url.trim(),
isFile = /\b.(jpg|bmp|jpeg|gif|png|tif)\b$/;
image = isFile.test(path.toLowerCase());
path = path.split("/");
if (image) { // If we detect image file name at end, get filename
image = path.pop();
}
path = path.join("/").trim();
requestParams = {
album: path,
photo: image
};
}
var getterFunction = (image) ? gallery.getPhoto : gallery.getAlbum;
getterFunction.apply(gallery, [requestParams,
function (err, data) {
req.gallery = data;
return next(err);
//Should we do this here? res.render(data.type + '.ejs', data);
}
]);
}
}
};
function searchAlbum(alb, hash) {
if (alb.hash == hash) return alb;
var als = alb.albums;
var node = undefined;
for (var i = 0; i < als.length; i++) {
node = searchAlbum(als[i], hash);
if (node) {
return node;
}
}
return null;
};
module.exports = gallery;