This repository has been archived by the owner on Oct 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
308 lines (293 loc) · 7.5 KB
/
index.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
'use strict';
const exif = require('fast-exif');
const mustache = require('mustache');
const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const configFile = path.join(
__dirname,
'config.json'
);
const templatePath = path.join(
__dirname,
'template.mustache'
);
const exitCode = {
incorrectArguments: 1
};
let inputDirectory = null;
let thumbnailsDirectory = null;
let generatedPagePath = null;
let gmPath = null;
let photos = null;
/**
* Prints program usage.
*/
function usage() {
const scriptPath = process.argv[1];
console.error(`Usage: node ${scriptPath} <input-dir>`);
}
/**
* Checks if the given directory is valid.
*
* @param {String} directory Directory path.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function checkDirectory(directory) {
return new Promise((resolve, reject) => {
fs.stat(directory, (error, stats) => {
if (error !== null) {
reject(error);
return;
}
if (!stats.isDirectory()) {
const errorMessage = `${directory} is not a directory.`;
reject(new Error(errorMessage));
return;
}
resolve();
});
});
}
/**
* Gets configurations, including the path of GraphicsMagick.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function getConfigurations() {
return new Promise((resolve, reject) => {
fs.readFile(
configFile,
{
encoding: 'utf8'
},
(error, data) => {
if (error !== null) {
reject(error);
return;
}
try {
const config = JSON.parse(data);
if (!config.gmPath) {
reject(new Error('Path of GraphicsMagick is unspecified'));
return;
}
gmPath = config.gmPath;
resolve();
} catch (parseError) {
reject(parseError);
}
});
});
}
/**
* Gets filenames of photos from the given directory.
*
* The photos array is initialized with objects which each contains the filename
* and the absolute path of the photo.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function getPhotos() {
return new Promise((resolve, reject) => {
fs.readdir(inputDirectory, (error, filenames) => {
if (error !== null) {
reject(error);
return;
}
photos = [];
filenames.forEach((filename) => {
photos.push({
filename: filename,
path: path.join(inputDirectory, filename)
});
});
resolve();
});
});
}
/**
* Gets modification time of the photo.
*
* The modification time of each photo is added to the objects in the photos
* array. The modification time is represented in ISO8601 format up to seconds
* part. The timezone of the modification time is the one used in the location
* where the photo was taken.
*
* @param {String} photoPath Path of the photo.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function getPhotoModificationTime(photoPath) {
return new Promise((resolve, reject) => {
exif.read(photoPath)
.then((metadata) => {
if (!metadata) {
reject(new Error(`No metadata in ${photoPath}.`));
return;
}
if (!metadata.exif) {
reject(new Error(`No EXIF data in ${photoPath}.`));
return;
}
if (!metadata.exif.DateTimeOriginal) {
reject(new Error(`Cannot find modification time in ${photoPath}.`));
return;
}
let modificationTime = metadata.exif.DateTimeOriginal.toISOString();
modificationTime = modificationTime.substring(
0,
modificationTime.indexOf('.')
);
for (let i = 0; i < photos.length; i += 1) {
const photo = photos[i];
if (photo.path === photoPath) {
photo.modificationTime = modificationTime;
break;
}
}
resolve();
})
.catch((error) => {
reject(error);
});
});
}
/**
* Gets photos' modification time.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function getPhotosModificationTime() {
return new Promise((resolve, reject) => {
const promises = [];
photos.forEach((photo) => {
promises.push(getPhotoModificationTime(photo.path));
});
Promise.all(promises)
.then(() => {
resolve();
})
.catch((error) => {
reject(error);
});
});
}
/**
* Creates thumbnails directory.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function createThumbnailsDirectory() {
return new Promise((resolve, reject) => {
fs.mkdir(thumbnailsDirectory, (error) => {
if (error !== null) {
reject(error);
return;
}
resolve();
});
});
}
/**
* Resizes photos in batch using GraphicsMagick.
*
* @returns {Promise} Resolves with success, or rejects with an Error object.
*/
function batchResize() {
return new Promise((resolve, reject) => {
const commandArguments = [
'batch',
'-'
];
const gm = childProcess.spawn(gmPath, commandArguments);
gm.on('error', (error) => {
reject(error);
gm.kill();
});
gm.on('close', (code) => {
if (code !== 0) {
reject(new Error(`GraphicsMagick exit with code ${code}`));
return;
}
resolve();
});
const batchCommands = [];
photos.forEach((photo) => {
const thumbnailPath = path.join(thumbnailsDirectory, photo.filename);
const command = [
'convert',
'-auto-orient',
'-geometry',
'1280x720>',
'+profile',
'"*"',
photo.path,
thumbnailPath,
'\n'
].join(' ');
batchCommands.push(command);
});
gm.stdin.write(batchCommands.join(''));
gm.stdin.end();
});
}
/**
* Generates a page (HTML document) using the photos.
*
* @returns {Promise} Resolves successfully, or rejects with an Error object.
*/
function generatePage() {
return new Promise((resolve, reject) => {
fs.readFile(
templatePath,
{
encoding: 'utf8'
},
(readTemplateError, template) => {
if (readTemplateError !== null) {
reject(readTemplateError);
return;
}
const view = {
currentTimestamp: (new Date()).toISOString(),
photos: []
};
photos.forEach((photo) => {
view.photos.push({
filename: photo.filename,
altText: `Photo captured at ${photo.modificationTime}.`,
timestamp: photo.modificationTime
});
});
const generatedContent = mustache.render(template, view);
fs.writeFile(generatedPagePath, generatedContent, (writePageError) => {
if (writePageError !== null) {
reject(writePageError);
return;
}
resolve();
});
});
});
}
if (process.argv.length !== 3) {
usage();
process.exit(exitCode.incorrectArguments);
} else {
inputDirectory = process.argv[2];
thumbnailsDirectory = path.join(inputDirectory, 'thumbnails');
generatedPagePath = path.join(inputDirectory, 'index.html');
}
Promise.resolve(inputDirectory)
.then(checkDirectory)
.then(getConfigurations)
.then(getPhotos)
.then(getPhotosModificationTime)
.then(createThumbnailsDirectory)
.then(batchResize)
.then(generatePage)
.catch((error) => {
console.error(error);
});