-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
495 lines (460 loc) · 17.6 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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
#!/usr/bin/env node
'use strict';
const commander = require('commander');
const argv = commander
.option('-a, --attempts [num]', 'number of times to try to connect to Photobucket', parseInt, 3)
.option('-f, --fake', 'simulate (don\'t download anything)', false)
.option('-m, --media-timeout [ms]', 'time between requests (in milliseconds) to Photobucket\'s media servers', parseInt, 500)
//.option('-l, --links [file]', 'write image links to a file instead of downloading them')
.option('-o, --output [path]', 'file/directory that media is saved to/in (if directory, will be created if it doesn\'t exist)')
.option('-r, --recursive', 'if album, get subalbums (including their subalbums)', false)
.option('-s, --site-timeout [ms]', 'time between requests (in milliseconds) to Photobucket\'s website/API', parseInt, 2000)
.option('-u, --url <url>', 'URL of the file/album')
.option('-v, --verbose', 'describe every minute detail in every step we do', false)
.parse(process.argv);
if (process.argv.length === 2) {
commander.help();
process.exit(1);
}
argv.options.forEach((option) => {
if (option.required !== 0 && typeof argv[option.long.slice(2)] === 'undefined') {
console.log('\n error: missing required parameter \'%s\'', option.long);
process.exit(1);
}
});
if (typeof argv.output === 'undefined' && typeof argv.links === 'undefined') {
console.log('\n error: missing required parameter \'--links\' or \'--output\'');
process.exit(1);
}
const async = require('async');
const extend = require('deep-extend');
const fs = require('fs-extra');
const path = require('path');
const request = require('request');
const touch = require('touch');
const url = require('url');
function opts(custom) {
return extend({
headers: {
'accept-language': 'en-US,en;q=0.8',
'content-type': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
},
gzip: true,
method: 'GET',
}, custom);
}
function apiOpts(custom) {
return extend(opts({
headers: {
accept: 'application/json, text/javascript, */*; q=0.01',
'x-requested-with': 'XMLHttpRequest',
},
qs: {
json: 1,
},
}), custom);
}
function retry(timeout, task, fnCb) {
let attempts = 0;
async.retry({
interval: timeout,
times: argv.attempts,
}, (retryCb) => {
attempts += 1;
if (attempts === 1) {
setTimeout(() => {
task(retryCb);
}, timeout);
} else {
task(retryCb);
}
}, fnCb);
}
function req(customOpts, reqCb) {
retry(argv.siteTimeout, (retryCb) => {
if (argv.verbose) {
if (typeof customOpts.qs !== 'undefined' && typeof customOpts.qs.page !== 'undefined') {
console.log(`Trying ${customOpts.uri}... (page #${customOpts.qs.page})`);
} else {
console.log(`Trying ${customOpts.uri}...`);
}
}
setTimeout(() => {
request(customOpts, (reqErr, _, reqBody) => {
if (reqErr === null) {
return retryCb(null, reqBody);
} else {
return retryCb(reqErr, null);
}
});
}, argv.siteTimeout);
}, reqCb);
}
function apiReq(customOpts, reqCb) {
req(customOpts, (reqErr, reqBody) => {
if (reqErr === null) {
let data = {};
try {
data = JSON.parse(reqBody);
} catch (jsonErr) {
if (argv.verbose) {
console.log({
status: 'jsonErr',
opts: customOpts,
err: reqErr,
res: reqBody,
});
}
return reqCb(jsonErr, null);
}
if (argv.verbose) {
console.log({
status: 'normal',
opts: customOpts,
err: reqErr,
res: data,
});
}
return reqCb(null, data);
} else {
if (argv.verbose) {
console.log({
status: 'reqErr',
opts: customOpts,
err: reqErr,
res: reqBody,
});
}
return reqCb(reqErr, null);
}
});
}
class File {
constructor(rawUrl, fns) {
this.type = 'file';
this.url = rawUrl;
this.filename = path.parse(this.url).base;
if (typeof fns !== 'undefined') {
this.fns = fns;
} else {
this.fns = {};
}
}
static fromObj(obj, fns) {
return new File(obj.fullsizeUrl, typeof fns === 'object' ? fns : undefined);
}
download(toPath, cb) {
if (typeof this.fns.beforeDl === 'function') {
this.fns.beforeDl(this);
}
if (!argv.fake) {
retry(argv.mediaTimeout, (retryCb) => {
fs.ensureDirSync(path.parse(toPath).dir);
const fileStream = fs.createWriteStream(toPath);
let created = '';
fileStream.on('close', () => {
if (typeof this.fns.afterDl === 'function') {
this.fns.afterDl(this);
}
if (created !== '') {
touch(toPath, {
mtime: new Date(created),
}, () => {
return retryCb(null);
});
}
});
setTimeout(() => {
request({
accept: 'image/webp,image/*',
uri: this.url,
}, (reqErr, reqRes) => {
if (reqErr === null) {
if (typeof reqRes.headers['last-modified'] === 'string') {
created = reqRes.headers['last-modified'];
}
} else {
retryCb(reqErr);
}
}).on('error', (reqErr) => {
if (reqErr !== null) {
return retryCb(reqErr);
}
}).pipe(fileStream);
}, argv.mediaTimeout);
}, cb);
} else {
cb(null);
}
}
}
class Album {
constructor(originalUrl, albumPath, fns) {
this.url = url.parse(originalUrl);
this.type = 'album';
this.path = albumPath;
this.perPage = 24;
this.total = null;
if (typeof fns !== 'undefined') {
this.fns = fns;
} else {
this.fns = {};
}
}
page(num, cb, fns) {
if (typeof this.fns.beforePage === 'function') {
this.fns.beforePage(num);
}
apiReq(apiOpts({
qs: {
'filters[album]': this.path,
limit: this.perPage, // page uses 24 by default
page: num,
},
uri: `${this.url.protocol}//${this.url.hostname}/component/Common-PageCollection-Album-AlbumPageCollection`,
}), (reqErr, reqBody) => {
if (reqErr === null) {
this.total = reqBody.body.total;
if (typeof this.fns.afterPage === 'function') {
this.fns.afterPage(num);
}
return cb(null, {
files: reqBody.body.objects.map((obj) => {
return File.fromObj(obj, typeof fns === 'object' ? fns : undefined);
}),
offset: reqBody.body.currentOffset,
total: this.total,
});
} else {
return cb(reqErr, null);
}
});
}
files(cb, fns) {
let out = [];
this.page(1, (pageErr, pageData) => {
if (pageErr === null) {
out = pageData.files;
let pagesNeeded = 0;
if (this.total > 0) {
while (pagesNeeded * this.perPage < this.total) {
pagesNeeded += 1;
}
pagesNeeded -= 1; // because we already did the first page
return async.mapSeries([...Array(pagesNeeded).keys()].map((num) => {
return num + 2;
}), (num, mapCb) => {
this.page(num, (mapPageErr, mapPageData) => {
if (mapPageErr === null) {
return mapCb(null, mapPageData.files);
} else {
return mapCb(mapPageErr, null);
}
}, typeof fns === 'object' ? fns : undefined);
}, (mapErr, mapData) => {
if (mapErr === null) {
mapData.forEach((page) => {
out = out.concat(page);
});
return cb(null, out);
} else {
return cb(mapErr, null);
}
});
} else {
cb(null, []);
}
} else {
return cb(pageErr, null);
}
}, typeof fns === 'object' ? fns : undefined);
}
download(directory, cb, recursive, recursiveFns) {
if (typeof this.fns.afterAlbumDl === 'function') {
this.fns.beforeAlbumDl();
}
this.files((filesErr, filesData) => {
if (filesErr === null) {
async.eachSeries(filesData, (file, fileEachCb) => {
file.download(directory + file.filename, (dlErr) => {
fileEachCb(dlErr);
});
}, (eachErr) => {
if (eachErr === null) {
if (typeof this.fns.afterAlbumDl === 'function') {
this.fns.afterAlbumDl();
}
if (recursive) {
this.subalbums((subalbumsErr, subalbumsData) => {
if (subalbumsErr === null) {
if (subalbumsData.length === 0) {
if (typeof this.fns.noSubAlbums === 'function') {
this.fns.noSubAlbums();
}
} else {
if (typeof this.fns.beforeRecursiveAlbumDl === 'function') {
this.fns.beforeRecursiveAlbumDl(subalbumsData.length);
}
}
async.eachSeries(subalbumsData, (subalbum, subalbumEachCb) => {
console.log(subalbum);
subalbum.album.download(`${directory + subalbum.title.replace(/[\\/><|:&"?*]/g, '_')}/`, subalbumEachCb, true);
}, (subalbumDlErr) => {
if (subalbumDlErr === null) {
if (typeof this.fns.afterRecursiveAlbumDl === 'function') {
this.fns.afterRecursiveAlbumDl();
}
cb(null);
} else {
cb(subalbumDlErr);
}
});
} else {
cb(subalbumsErr);
}
}, recursiveFns ? this.fns : undefined);
} else {
cb(null);
}
} else {
cb(eachErr);
}
});
} else {
cb(filesErr);
}
});
}
subalbums(cb, fns) {
apiReq(apiOpts({
qs: {
albumPath: this.path,
fetchSubAlbumsOnly: true,
deferCollapsed: true,
},
uri: `${this.url.protocol}//${this.url.hostname}/component/Albums-SubalbumList`,
}), (reqErr, reqBody) => {
if (reqErr === null) {
if (typeof fns === 'object') {
cb(null, reqBody.body.subAlbums.map((subalbum) => {
return {
album: new Album(subalbum.linkUrl, subalbum.path, typeof fns === 'object' ? fns : undefined),
title: subalbum.title,
};
}));
} else {
cb(null, reqBody.body.subAlbums.map((subalbum) => {
return {
album: new Album(subalbum.linkUrl, subalbum.path, typeof fns === 'object' ? fns : undefined),
title: subalbum.title,
};
}));
}
} else {
cb(reqErr, null);
}
});
}
}
function handleUrl(originalUrl, cb, fns) {
const fixedUrl = `${(originalUrl.indexOf('http') === 0 ? originalUrl : `http://${originalUrl}`).split('?')[0]}?page=1`;
req(opts({
uri: fixedUrl,
}), (reqErr, reqBody) => {
if (reqErr === null) {
const lines = reqBody.split('\n');
let albumPathAttempt = lines.filter((line) => {
return line.indexOf('queryObj:') > -1 && line.indexOf('"album":') > -1;
});
if (albumPathAttempt.length === 1) {
albumPathAttempt = /\s*queryObj:\s?{.+"album":"([%\w\d\s\\\/]+)",.+},/.exec(albumPathAttempt[0]);
if (albumPathAttempt === null) {
return cb('Couldn\'t parse album object data from webpage.', null);
} else {
if (typeof fns === 'object') {
return cb(null, new Album(fixedUrl, JSON.parse(`"${albumPathAttempt[1]}"`), fns));
} else {
return cb(null, new Album(fixedUrl, JSON.parse(`"${albumPathAttempt[1]}"`)));
}
}
} else {
let fileObjAttempt = lines.filter((line) => {
return line.indexOf('Pb.Data.Shared.MEDIA') > -1 && line.indexOf('"originalUrl":') > -1;
});
if (fileObjAttempt.length === 1) {
fileObjAttempt = /"fullsizeUrl":"([:%\w\d\/\\\.]+)"/.exec(fileObjAttempt[0]);
if (fileObjAttempt === null) {
return cb('Couldn\'t parse file object data from webpage.', null);
} else {
if (typeof fns === 'object') {
return cb(null, new File(JSON.parse(`"${fileObjAttempt[1]}"`), fns));
} else {
return cb(null, new File(JSON.parse(`"${fileObjAttempt[1]}"`)));
}
}
} else {
return cb('Cannot parse data from URL.', null);
}
}
} else {
return cb(reqErr, null);
}
});
}
const fns = {
beforeDl: (file) => {
console.log(`Downloading "${file.filename}"...`);
},
afterDl: (file) => {
console.log(`Downloading "${file.filename}"... done.`);
},
beforePage: (page) => {
console.log(`Getting files from page ${page}...`);
},
afterPage: (page) => {
console.log(`Getting files from page ${page}... done.`);
},
beforeAlbumDl: () => {
console.log('Getting album...');
},
afterAlbumDl: () => {
console.log('Getting album... done.');
},
beforeRecursiveAlbumDl: (len) => {
console.log(`\nChecking for subalbum(s)... ${len}.`);
console.log('Getting subalbum(s)...');
},
afterRecursiveAlbumDl: () => {
console.log('Getting subalbum(s)... done.\n');
},
noSubAlbums: () => {
console.log('\nChecking for subalbum(s)... 0.');
},
};
handleUrl(argv.url, (handleErr, handleData) => {
if (handleErr === null) {
if (handleData.type === 'album') {
if (argv.output[argv.output.length - 1] !== '/') {
argv.output += '/';
}
handleData.download(argv.output, (origDlErr) => {
if (origDlErr === null) {
console.log('\nDone!');
} else {
console.log(origDlErr);
}
}, argv.recursive, argv.recursive);
} else {
handleData.download(argv.output, (origDlErr) => {
if (origDlErr === null) {
console.log('\nDone!');
} else {
console.log(origDlErr);
}
});
}
} else {
console.log(handleErr);
}
}, fns);