-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsadkitty.js
980 lines (770 loc) · 26.8 KB
/
sadkitty.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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
import fs from 'fs/promises';
import puppeteer from 'puppeteer-extra';
import sqlite3 from 'sqlite3';
import Downloader from 'nodejs-file-downloader';
import commandLineArgs from 'command-line-args';
import rimraf from 'rimraf';
import prompts from 'prompts';
import chalk from 'chalk';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import { CMD_LINE_OPTIONS } from './constants.js';
import { logger } from './logger.js';
// command-line
const Options = commandLineArgs(CMD_LINE_OPTIONS);
// files
const fsUnlinkPromise = async (path) => {
return fs
.unlink(path)
.then((path) => path)
.catch((error) => error);
};
const rimrafPromise = (path, options = {}) => {
return new Promise((resolve, reject) => {
rimraf(path, options, (error) => {
if (error) {
return reject(error);
}
resolve(path);
});
});
};
// database
fs.stat('./storage.db', (err) => {
if (err) {
let db = new sqlite3.Database('./storage.db', (_err) => {
db.close();
});
}
});
let db = new sqlite3.Database('./storage.db');
const dbGetPromise = (sql, ...params) => {
return new Promise((resolve, reject) => {
db.get(sql, ...params, (err, row) => {
if (err) {
return reject(err);
}
resolve(row);
});
});
};
const dbRunPromise = (sql, params) => {
return new Promise((resolve, reject) => {
db.run(sql, params, (result, err) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
};
const dbAllPromise = (sql, params) => {
return new Promise((resolve, reject) => {
db.all(sql, params, (err, rows) => {
if (err) {
return reject(err);
}
resolve(rows);
});
});
};
function getCleanUrl(source) {
const url = new URL(source);
return `${url.protocol}//${url.hostname}${url.pathname}`;
}
// schema
db.run(`CREATE TABLE IF NOT EXISTS Author (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
url TEXT
)`);
db.run(`CREATE TABLE IF NOT EXISTS Post (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author_id TEXT NOT NULL,
url TEXT NOT NULL,
description TEXT,
timestamp TEXT,
locked INTEGER,
cache_media_count INTEGER
)`);
db.run(`CREATE TABLE IF NOT EXISTS Media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
url TEXT NOT NULL,
file_path TEXT
)`);
// scraping
let lastUrl = '';
let browser = null;
let loggedIn = false;
const waitForPagePromise = () => {
return new Promise((resolve) => {
if (browser !== null && loggedIn) {
return resolve(browser);
}
const checkBrowser = setInterval(() => {
logger.info('Checking for browser...');
if (browser !== null && loggedIn) {
clearInterval(checkBrowser);
resolve(browser);
}
}, 1000);
}).then((resolved) => {
return resolved.pages().then((pages) => {
const [ page ] = pages;
return page;
});
});
}
async function getPageElement(page, selector, timeout = 100) {
try {
const element = await page.waitForSelector(selector, { timeout: timeout });
return element;
} catch (error) {
return null;
}
}
async function downloadMedia(url, index, author, post) {
// create directories
const authorPath = `./downloads/${author.id}`;
try {
await fs.mkdir(authorPath, { recursive: true });
} catch (error) {
logger.error(err);
}
// get path
const encoded = new URL(url);
const extension = encoded.pathname.split('.').pop();
/** @type {String} */
let fileName = post.description.replace(/[\\\/\:\*\?\"\<\>\|\. ]/g, '_');
fileName = encodeURIComponent(fileName);
fileName = fileName.replace(/_/g, ' ');
if (fileName.length > 80) {
fileName = fileName.substr(0, 80);
}
fileName = `[${author.id}] ` + fileName;
const postMatch = post.url.match(/.*\/(\d+).*/);
fileName += ` [${postMatch[1]}]`;
if (index > 0) {
fileName += ` (${index + 1})`;
}
fileName += '.' + extension;
const dstPath = authorPath + '/' + fileName;
// download file
logger.info(`Downloading "${dstPath.split('/').pop()}"...`);
let timeStart = Date.now();
const downloader = new Downloader({
url: url,
directory: authorPath,
fileName: fileName,
maxAttempts: 3,
cloneFiles: true, // don't overwrite existing files
shouldStop: (error) => {
logger.error(error);
return false;
},
onProgress: (percentage, _chunk, _remainingSize) => {
if (Date.now() - timeStart < 10 * 1000) {
return;
}
timeStart = Date.now();
const barBefore = Math.floor(percentage / 10);
const barAfter = 10 - barBefore;
logger.info(`[ ${'#'.repeat(barBefore)}${'.'.repeat(barAfter)} ] ${percentage}%`);
},
});
try {
await downloader.download();
await fs.copyFile(dstPath, './downloads/new/' + fileName);
logger.info(`Succeeded.`);
return dstPath;
} catch (error) {
logger.error(`Failed to download: ${error.message}`);
return '';
}
}
async function scrapePost(url, author, postIndex, postTotal) {
logger.info(`(${postIndex + 1} / ${postTotal}) Scraping sources from "${url}"...`);
lastUrl = url;
const page = await waitForPagePromise();
// load page and wait for post to appear
let attempt = 1;
for (attempt = 1; attempt < 4; ++attempt) {
if (attempt > 1) {
logger.warn(`Attempt ${attempt + 1} to scrape page...`);
}
try {
await page.goto(url, {
waitUntil: 'domcontentloaded',
timeout: 10 * 1000,
});
await page.waitForSelector('.b-post__wrapper', {
timeout: 10 * 1000,
});
break;
} catch (errors) {
logger.error('Failed to load page: ' + errors.message);
await page.reload();
}
}
if (attempt >= 3) {
logger.error(`Failed to load "${url}", continuing.`);
return 0;
}
// set up post
let post = {
id: 0,
description: '',
date: '',
url: url,
sources: [],
mediaCount: 0,
locked: 0,
};
// get sources
for (attempt = 1; attempt < 4; ++attempt) {
if (attempt > 1) {
logger.warn(`Attempt ${attempt} to scrape sources...`);
}
// check if post is locked
const eleLocked = await getPageElement(page, '.b-profile__restricted__icon', 1000);
if (eleLocked) {
logger.info('Post locked, continuing.');
post.locked = 1;
break;
}
// get video
const eleVideo = await getPageElement(page, '.video-js button', 1000);
if (eleVideo) {
logger.info('Found video.');
try {
eleVideo.click();
} catch (error) {
logger.error(`Failed to click play button: ${error.message}`);
continue;
}
let quality = '720';
const qualityLevels = ['720', 'original', '480', '240'];
for (let q in qualityLevels) {
try {
await page.waitForSelector(`video > source[label="${qualityLevels[q]}"]`, { timeout: 2000 });
quality = qualityLevels[q];
break;
} catch (error) {
continue;
}
}
logger.info(`Grabbing source at "${quality}" quality.`);
try {
const videoSource = await page.$eval(`video > source[label="${quality}"]`, (element) =>
element.getAttribute('src')
);
if (!post.sources.includes(videoSource)) {
post.sources.push(videoSource);
}
} catch (error) {
logger.error(`Failed to grab source: ${error.message}`);
continue;
}
}
// get image(s)
const eleSwiper = await getPageElement(page, '.swiper-wrapper', 1000);
if (eleSwiper) {
logger.info('Found multiple images.');
try {
const found = await page.$$eval('img[draggable="false"]', (elements) =>
elements.map((image) => image.getAttribute('src'))
);
found.forEach((imageSource) => {
if (!post.sources.includes(imageSource)) {
post.sources.push(imageSource);
}
});
} catch (error) {
logger.error('Failed to grab source: ' + error.message);
continue;
}
}
const eleImage = await getPageElement(page, '.img-responsive', 1000);
if (eleImage) {
logger.info('Found single image.');
try {
const imageSource = await page.$eval('.img-responsive', (element) => element.getAttribute('src'));
if (!post.sources.includes(imageSource)) {
post.sources.push(imageSource);
}
} catch (error) {
logger.error('Failed to grab source: ' + error.message);
continue;
}
}
if (post.sources.length > 0) {
break;
}
}
// get id
await dbGetPromise('SELECT id, cache_media_count FROM Post WHERE url = ?', [url]).then((row) => {
if (row) {
post.id = Number(row.id);
post.mediaCount = row.cache_media_count;
}
});
// get description
try {
post.description = await page.$eval('.b-post__text-el', (element) => element.innerText);
} catch (errors) {
post.description = 'none';
}
// get timestamp
post.date = await page.$eval('.b-post__date > span', (element) => element.innerText);
// create new post
if (post.id === 0) {
await dbRunPromise(
`INSERT INTO Post (
author_id,
url,
description,
timestamp,
locked,
cache_media_count
) VALUES (?, ?, ?, ?, ?, ?)`,
[author.id, post.url, encodeURIComponent(post.description), post.date, post.locked, post.mediaCount]
);
await dbGetPromise('SELECT id FROM Post WHERE url = ?', [url]).then((row) => {
post.id = Number(row.id);
});
}
if (post.sources.length === 0) {
logger.warn('Nothing to download.');
return 1;
}
let queue = [];
for (const source of post.sources) {
await dbGetPromise(
`SELECT *
FROM Media
WHERE post_id = ?
AND url = ?`,
[post.id, getCleanUrl(source)]
).then((row) => {
if (!row) {
queue.push(source);
}
});
}
if (queue.length > 0) {
logger.info(`Queueing ${queue.length} download(s)...`);
let index = 0;
for (const source of queue) {
const filePath = await downloadMedia(source, index, author, post);
if (filePath === '') {
continue;
}
// update media count
post.mediaCount += 1;
await dbRunPromise(
`UPDATE Post
SET cache_media_count = ?
WHERE id = ?`,
[post.mediaCount, post.id]
);
// add media to database
await dbRunPromise(
`INSERT INTO Media (
post_id,
url,
file_path
) VALUES (?, ?, ?)`,
[post.id, getCleanUrl(source), filePath]
);
index += 1;
}
} else {
post.mediaCount = post.sources.length;
await dbRunPromise(
`UPDATE Post
SET cache_media_count = ?
WHERE id = ?`,
[post.mediaCount, post.id]
);
}
return post.mediaCount;
}
async function scrapeMediaPage(db, author) {
logger.info(`Checking posts from ${author.name}...`);
const page = await waitForPagePromise();
// wait for page to load
let attempt = 1;
for (attempt = 1; attempt < 4; ++attempt) {
if (attempt > 1) {
logger.info(`Attempt ${attempt} to load media page...`);
}
try {
await page.goto(`https://onlyfans.com/${author.id}/media?order=publish_date_desc`, {
waitUntil: 'networkidle0',
timeout: 10 * 1000,
});
await page.waitForSelector('.b-feed-content', {
timeout: 10 * 1000,
});
break;
} catch (errors) {
logger.error('Failed to load page: ' + errors.message);
await page.reload();
}
}
if (attempt >= 3) {
logger.error('Failed to scrape media page.');
return;
}
// get all seen posts
let seenPosts = [];
await dbAllPromise(
`SELECT *
FROM Post
WHERE author_id = ?
AND cache_media_count > 0`,
author.id
).then((rows) => {
seenPosts = rows.map((row) => Number(row.url.match(/.*\/(\d+).*/)[1]));
});
// scroll down automatically every 3s
const unseenPosts = await page.evaluate(async (seenPosts) => {
let unseenPosts = [];
await new Promise((resolve, _reject) => {
let totalHeight = 0;
let nothingFound = 0;
const MAX_ATTEMPTS = 5;
const timer = setInterval(() => {
let scrollHeight = document.body.scrollHeight;
let distance = document.body.scrollHeight - window.innerHeight - window.scrollY;
window.scrollBy(0, distance);
totalHeight += distance;
console.log(`scrollHeight ${scrollHeight} totalHeight ${totalHeight} distance ${distance}`);
// filter unique posts from elements
const found = Array.from(document.querySelectorAll('.b-photos__item'))
.map(post => Number(post.getAttribute('data-id')));
const foundUnique = found.filter((id, index) => found.indexOf(id) === index);
const foundUnseen = [];
foundUnique.forEach((id) => {
if (!seenPosts.includes(id) && !unseenPosts.includes(id)) {
foundUnseen.push(id);
}
});
console.log(`Found ${foundUnseen.length} new posts...`);
if (foundUnseen.length === 0) {
nothingFound++;
console.log(`Counter: ${nothingFound}`);
} else {
nothingFound = 0;
}
unseenPosts = unseenPosts.concat(foundUnseen);
// console.log(unseenPosts);
console.log(`Total: ${unseenPosts.length}`);
// check if we've scrolled down the entire page
if (seenPosts.length === 0) {
if (distance === 0) {
nothingFound = MAX_ATTEMPTS;
} else {
nothingFound = 0;
}
}
// check if no posts have been found after multiple retries
if (nothingFound === MAX_ATTEMPTS) {
clearInterval(timer);
resolve(unseenPosts);
}
}, 2000);
});
return unseenPosts;
}, seenPosts);
// get posts
if (unseenPosts.length === 0) {
logger.info('All posts seen.');
return;
}
// oldest to newest
unseenPosts.reverse();
logger.info(`Found ${unseenPosts.length} post(s).`);
const scrapingFailed = [];
for (const [index, id] of unseenPosts.entries()) {
const url = `https://onlyfans.com/${id}/${author.id}`;
try {
const scraped = await scrapePost(url, author, index, unseenPosts.length);
if (scraped < 1) {
scrapingFailed.push(url);
}
} catch (error) {
logger.error(`Caught error while scraping "${url}": ${error}`);
scrapingFailed.push(url);
}
}
logger.info(`Scraped ${unseenPosts.length} post(s) from ${author.name}.`);
if (scrapingFailed.length > 0) {
logger.error(`Failed to scrape: ${scrapingFailed}`);
}
}
async function setup() {
const onCancel = () => process.exit(0);
logger.warn('Setting up authentication for OnlyFans.\n');
logger.info('Checking for existing authentication data...\n');
let existingAuthData = { username: '', password: '' };
try {
existingAuthData = JSON.parse((await fs.readFile('auth.json', { encoding: 'utf8' })) || {});
if (Object.keys(existingAuthData || {}).length > 0) {
logger.info('Auth data found! Skip prompts for input by pressing Enter.\n');
}
} catch (error) {
// Error logs could be hidden behind a command line flag in the future
logger.error(`Error parsing file ▶ ${error}`);
}
const { username, password } = existingAuthData;
const existingUsername = username ? chalk.yellow.bgBlack` (${username})` : '';
const existingPassword = password ? chalk.yellow.bgBlack` (${password.substr(0, 3)}******)` : '';
/** @type {import('prompts').PromptObject<string>[]} */
const authQuestions = [
{
type: 'text',
name: 'username',
message: `Username${existingUsername}: `,
initial: username,
},
{
type: 'password',
name: 'password',
message: `Password${existingPassword}: `,
initial: password,
},
];
const auth = await prompts(authQuestions, { onCancel });
await fs.writeFile('auth.json', JSON.stringify(auth));
logger.info('Saved as "auth.json"\n');
/** @type {{ name: String, id: String}[]} */
let existingCreatorData;
try {
existingCreatorData = JSON.parse((await fs.readFile('authors.json', { encoding: 'utf8' })) || {});
if (Object.keys(existingCreatorData || {}).length > 0)
logger.info('Existing creator data will be shown in brackets. Skip prompts for input by pressing Enter.\n');
} catch (error) {
// Error logs could be hidden behind a command line flag in the future
logger.error(`Error parsing file ▶ ${error}`);
}
const existingCreatorCount = existingCreatorData ? Object.keys(existingCreatorData || {}).length : 1;
const formattedCreatorCount = existingCreatorData ? chalk.yellow.bgBlack` (${existingCreatorCount})` : '';
logger.info('How many creators would you like to scrape?');
const numCreatorsQ = await prompts(
{
name: 'response',
type: 'number',
message: `Number of creators${formattedCreatorCount}: `,
initial: existingCreatorCount,
},
{
onCancel
}
);
/** @type {import('prompts').PromptObject<string>[]} */
const creatorQuestions = Array.from({ length: numCreatorsQ.response }, () => {}).flatMap(
/** @returns {import('prompts').PromptObject<string>[]} */
(_, index) => {
const existingCreator = existingCreatorData?.[index] || false;
const existingName = existingCreator
? chalk.yellow.bgBlack` (${existingCreator.name} @${existingCreator.id})`
: '';
const existingID = existingCreator ? chalk.yellow.bgBlack`${existingCreator.id}` : '<their_creator_id>';
return [
{
type: 'text',
name: 'name',
message: `Name of creator #${index + 1}${existingName}: `,
initial: existingCreator.name,
},
{
type: 'text',
name: 'id',
message: `OnlyFans ID for creator #${index + 1} (https://onlyfans.com/${existingID}): `,
initial: existingCreator.id,
},
];
}
);
const authors = [];
let tempValues = { name: '', id: '' };
/** @type {import('prompts').Options["onSubmit"]} */
const onSubmit = (prompt, answer) => {
if (prompt.name === 'name') {
tempValues = {};
tempValues.name = answer;
} else if (prompt.name === 'id') {
tempValues.id = answer;
authors.push(tempValues);
}
};
await prompts(creatorQuestions, { onCancel, onSubmit });
await fs.writeFile('authors.json', JSON.stringify(authors));
logger.info('Saved as "authors.json"\n');
logger.info('Ready to start scraping!');
process.exit(0);
}
async function scrape() {
// authentication
let auth;
try {
auth = JSON.parse((await fs.readFile('auth.json')) || {});
if (Object.keys(auth).length !== 2) throw new Error();
} catch (error) {
logger.error('Missing authentication data!');
logger.info('Create an "auth.json" file in this folder with the following:');
logger(
JSON.stringify({
username: '[email protected]',
password: 'supersecure',
})
);
process.exit(0);
}
// get authors
let authors = [];
let authorData = [];
try {
authorData = JSON.parse((await fs.readFile('authors.json')) || {});
if (!Object.keys(authorData)) throw new Error();
} catch (error) {
logger.error("Missing creator's data!");
logger.info('Create an "authors.json" in this folder:');
logger(
JSON.stringify([
{
id: 'found_in_the_onlyfans_url',
name: 'How you want the Artist to appear',
},
])
);
process.exit(0);
}
for (const data of authorData) {
await dbRunPromise(`INSERT OR IGNORE INTO Author (id, name, url) VALUES (?, ?, ?)`, [
data.id,
data.name,
`https://onlyfans.com/${data.id}`,
]);
await dbGetPromise('SELECT * FROM Author WHERE id = ?', data.id).then((author) => {
authors.push(author);
});
}
// hide puppeteer usage
puppeteer.use(StealthPlugin());
// open browser
let createBrowser = async () => {
browser = null;
loggedIn = false;
logger.info('Launching browser...');
browser = await puppeteer.launch({
ignoreHTTPSErrors: true,
headless: false,
args: [
'--window-size=1920,1080',
'--window-position=000,000',
'--disable-dev-shm-usage',
'--no-sandbox',
'--disable-web-security',
'--disable-features=site-per-process',
],
});
browser.on('disconnected', async () => {
logger.error('Connection lost, opening browser again.');
await createBrowser();
});
const [ page ] = await browser.pages();
logger.info('Loading main page...');
await page.goto('https://onlyfans.com', {
waitUntil: 'domcontentloaded',
});
await page.waitForSelector('form.b-loginreg__form');
// log in using twitter
logger.info('Logging in...');
await page.click('input[name="email"]');
await page.type('input[name="email"]', auth.username, { delay: 10 });
await page.click('input[name="password"]');
await page.type('input[name="password"]', auth.password, { delay: 10 });
await page.click('button[type="submit"]');
logger.info('Waiting for reCAPTCHA...');
let attempt = 1;
for (attempt = 1; attempt < 6; attempt++) {
try {
await page.waitForSelector('.user_posts', { timeout: 60 * 1000 });
break;
} catch (error) {
if (attempt > 1) {
logger.warn(`Checking for reCAPTCHA again in 1 minute...`);
}
}
}
if (attempt >= 5) {
logger.error('Timed out on reCAPTCHA.');
process.exit(0);
}
logger.info('Logged in.');
loggedIn = true;
if (lastUrl !== '') {
logger.warn(`Loading "${lastUrl}" again...`);
await page.goto(lastUrl, {
waitUntil: 'domcontentloaded',
timeout: 10 * 1000
});
}
}
await createBrowser();
// clear downloads
logger.info('Clearing downloads folder.');
await rimrafPromise('./downloads/new');
fs.mkdir('./downloads/new', { recursive: true });
// scrape media pages
logger.info(`Visiting ${authors.length} author(s).`);
for (const i in authors) {
const author = authors[i];
try {
await scrapeMediaPage(db, author);
} catch (error) {
logger.error(`Caught error while scraping page for ${author.name}: ${error}`);
}
}
logger.info('Done.');
db.close();
process.exit(0);
}
if (Options.setup) {
setup();
} else if (Options.deleteAuthor) {
(async () => {
logger.info(`Deleting "${Options.deleteAuthor}"...`);
let allPosts = [];
await dbAllPromise('SELECT * FROM Post WHERE author_id = ?', Options.deleteAuthor).then((authorPosts) => {
if (authorPosts) {
allPosts = authorPosts.map((post) => post.id);
}
});
let allMedia = [];
for (const id of allPosts) {
await dbGetPromise('SELECT * FROM Media WHERE post_id = ?', id).then((media) => {
if (media) {
allMedia.push(media);
}
});
}
logger.info(`Deleting ${allMedia.length} file(s)...`);
for (const media of allMedia) {
await fsUnlinkPromise(media.file_path);
await dbRunPromise('DELETE FROM Media WHERE id = ?', media.id);
}
logger.info(`Deleting ${allPosts.length} post(s)...`);
for (const id of allPosts) {
await dbRunPromise('DELETE FROM Post WHERE id = ?', id);
}
await dbRunPromise('DELETE FROM Author WHERE id = ?', Options.deleteAuthor);
logger.info(`Deleted "${Options.deleteAuthor}".`);
db.close();
process.exit(0);
})();
} else {
scrape();
}