-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
index.js
378 lines (334 loc) · 9.87 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
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
const request = require("request");
const fs = require("fs");
const https = require("https");
const path = require("path");
const ProgressBar = require("progress");
const inquirer = require("inquirer");
const { firstQuestions, nextQuestions } = require("./questions");
const bulksplash = async (args) => {
let basePath = "";
const options = {};
const ask = async () => {
await inquirer
.prompt([
{
type: "input",
name: "apiKey",
message: "🔑 What is your API key?",
},
{
type: "input",
name: "path",
message: "📂 Which directory do you want to save to?",
default: ".",
},
{
type: "list",
name: "random",
message: "📸 Which images do you want to download?",
choices: ["Random", "From a collection"],
filter: function (val) {
return val === "Random";
},
},
])
.then((answers) => {
options.random = answers.random;
options.apiKey = answers.apiKey;
basePath = answers.path === "." ? "" : answers.path;
});
if (options.random) {
// random
await inquirer
.prompt([
{
type: "input",
name: "search",
message: "🔍 What search term?",
},
])
.then((answers) => (options.search = answers.search));
} else {
// from a collection
await inquirer
.prompt([
{
type: "input",
name: "collection",
message:
"📎 Enter the URL of the Unsplash collection you want to download from",
validate: (value) => {
if (value.startsWith("https://unsplash.com/collections/")) {
return true;
}
return "🚨 Please enter a valid Unsplash Collections URL!";
},
},
])
.then((answers) => (options.collection = answers.collection));
}
await inquirer.prompt(firstQuestions).then((answers) => {
for (let a in answers) {
options[a] = answers[a];
}
});
if (options.random) {
if (options.orientation === "custom") {
await inquirer
.prompt([
nextQuestions({ required: true, side: "width" }),
nextQuestions({ required: true, side: "height" }),
])
.then((answers) => {
options.width = answers.width;
options.height = answers.height;
});
} else {
await inquirer
.prompt([nextQuestions({ required: false, side: "width" })])
.then((answers) => {
options.width = answers.width;
});
if (!options.width) {
await inquirer
.prompt([nextQuestions({ required: false, side: "height" })])
.then((answers) => {
options.height = answers.height;
});
}
}
}
if (options.orientation === "custom" || options.orientation === "mixed") {
delete options.orientation;
}
await inquirer
.prompt([
{
type: "confirm",
name: "saveCredits",
message: "🗂 Export the credits for the photos to a .json file?",
default: true,
},
])
.then((answers) => {
options.saveCredits = answers.saveCredits;
});
return options;
};
if (args.length != 0) {
args = require('minimist')(process.argv.slice(2));
basePath = args.d ? args.d : "";
options.random = true;
if (args.c && args.c.startsWith("https://unsplash.com/collections/")) {
options.random = false;
options.collection = args.c;
}
options.apiKey = args.k ? args.k : "";
options.search = args.q ? args.q : "";
options.amount = args.a && parseInt(args.a) > 0 ? parseInt(args.a) : 20;
options.width = args.w && parseInt(args.w) > 0 ? parseInt(args.w) : null;
options.height = args.h && parseInt(args.h) > 0 ? parseInt(args.h) : null;
options.orientation =
args.o && ["landscape", "portrait", "squarish"].includes(args.o)
? args.o
: "";
options.featured = args.f ? args.f : false;
options.nameScheme = args.n ? 0 : 1;
options.saveCredits = args.j ? args.j : false;
} else {
await ask();
}
// console.log(options)
const buildUrl = ({
featured,
order_by,
orientation,
search,
width,
height,
amount,
random,
collection,
apiKey,
}) => {
let base;
if (random) {
base = "https://api.unsplash.com/photos/random?";
} else if (collection) {
let collectionId = collection.split("/")[4];
base = `https://api.unsplash.com/collections/${collectionId}/photos?`;
}
const clientId = "&client_id=" + apiKey;
const f = random && featured ? "&featured" : "";
const ob = order_by ? "&order_by="+order_by:"";
const a = random ? (amount > 30 ? "&count=30" : `&count=${amount}`) : "";
const p =
!random && collection
? amount > 30
? "&per_page=30"
: `&per_page=${amount}`
: "";
const o = orientation ? `&orientation=${orientation}` : "";
const s = search && random ? `&query=${search}` : "";
const w = width ? `&w=${width}` : "";
const h = height ? `&h=${height}` : "";
return `${base}${a}${p}${o}${ob}${f}${w}${h}${s}${clientId}`;
};
let url;
console.log("\n🤖 Welcome to Bulksplash! (Powered by Unsplash.com)");
// eslint-disable-next-line max-len
console.log(
`\n🔰 Downloading ${options.amount}${options.featured ? " featured" : ""}${
options.search ? ' "' + options.search + '"' : ""
} images from:`
);
let bar;
let creditsAlreadyPrinted = {};
let c = 0;
const saveCredits = (credits, dest) => {
credits = Object.values(credits);
fs.writeFile(
dest + "/bulksplash-credits.json",
JSON.stringify(credits, null, "\t"),
"utf8",
(err) => {
if (err) {
return;
}
console.log(
"🗂 A .json file with details about the photographers has been saved to " +
dest +
"/bulksplash-credits.json\n"
);
}
);
};
const download = ({ imageUrl, dest, img, apiKey, width }) => {
let dir = path.parse(dest).dir;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
let { owner } = img;
if (!(owner.username in creditsAlreadyPrinted)) {
console.log(`📸 ${owner.name} (${owner.link})`);
creditsAlreadyPrinted[owner.username] = owner;
}
c += 1;
if (c == bar.total) {
console.log("\n⏳ Preparing download...\n");
}
const file = fs.createWriteStream(dest);
file.on(
"close",
() => {
bar.tick();
if (bar.complete) {
if (bar.total == options.amount) {
console.log("\n😌 All the photos have been downloaded!\n");
} else if (bar.total < options.amount) {
console.log(
"😔 There weren't enough images under the category you suggested, so we got as many as we could."
);
}
if (options.saveCredits) {
saveCredits(creditsAlreadyPrinted, dir);
}
}
},
{ once: true }
);
if (width) {
imageUrl += "&w=" + width;
}
https
.get(imageUrl, (response) => {
response.pipe(file);
})
.on("error", function (e) {
fs.unlink(dest, () => {});
console.log("🚨 Error while downloading", imageUrl, e.code);
});
// make request to Unsplash download endpoint to meet API requirements
// we don't download from endpoint because it deosn't let us download custom sizes
request(
`https://api.unsplash.com/photos/${img.id}/download?client_id=${apiKey}`,
(error, response, body) => {
// do nothing
}
);
};
let promises = [];
let images = [];
let iterations = 1;
let tAmount = options.amount - 30;
if (tAmount > 30) {
while (tAmount > 0) {
iterations += 1;
tAmount -= 30;
}
}
let processImages = () => {
return new Promise((resolve) => {
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
body = JSON.parse(body);
Object.values(body).forEach((v) => {
const img =
options.random && (options.width || options.height)
? v.urls.raw
: v.urls.full;
images.push({
imageUrl: img,
id: v.id,
owner: {
username: v.user.username,
name: v.user.name,
link: v.user.links.html,
},
});
});
resolve(images);
} else {
console.log(
`🚨 Something went wrong, got response code ${response.statusCode} from Unsplash - ${response.statusMessage}`
);
}
});
});
};
let page = 1;
for (let i = 0; i < iterations; i++) {
url = buildUrl(options);
if (options.random && options.amount > 30) {
options.amount -= 30;
} else if (!options.random && page <= iterations) {
options.amount -= 30;
url += "&page=" + page;
page += 1;
}
promises.push(processImages());
}
Promise.all(promises).then((images) => {
images = [].concat.apply([], [...new Set(images)]);
bar = new ProgressBar("🤩 DOWNLOADING [:bar]", {
total: images.length,
complete: "=",
incomplete: " ",
});
let imageNum = 1;
images.map((img) => {
download({
imageUrl: img.imageUrl,
dest: path.join(
process.cwd(),
`${basePath}/bulksplash-${img.owner.username}-${img.id}.jpg`
),
img,
apiKey: options.apiKey,
width: options.width,
});
imageNum += 1;
});
});
};
module.exports = bulksplash;