-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
149 lines (129 loc) · 5.3 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
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import puppeteer from 'puppeteer-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import fs from 'fs';
import c from 'chalk';
import slug from '@sindresorhus/slugify';
import _ from 'lodash';
import { downloadImage, ROOT, getCheerio, getPuppeteer } from './utils/index.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const fsP = fs.promises;
const args = process.argv.slice(2);
const NAME = args[0];
const scrap = async (page, { name, scrapBrands, scrapDetails }) => {
console.log(`Scraping ${c.bold.green(name)}...`);
const proms = [];
const group = { name };
try {
// Scrap for details
group.details = await scrapDetails(getCheerio(name), getPuppeteer(name, page));
} catch (e) {
console.log(`Error scraping ${c.bold.cyan('details')} for ${c.bold.red(name)}.`, e.toString());
}
try {
// Scrap websites
group.brands = await scrapBrands(getCheerio(name), getPuppeteer(name, page));
} catch (e) {
console.log(`Error scraping ${c.bold.cyan('website')} for ${c.bold.red(name)}.`, e.toString());
}
console.log(`Downloading pictures for ${c.bold.green(name)}...`);
const groupDir = path.join(ROOT, `./packages/website/public/img/${slug(name)}`);
// Ensure the dir exists.
await fsP.mkdir(groupDir, { recursive: true });
if (group.details.picture) {
proms.push(
new Promise(async (resolve) => {
const fileName = `${group.details.slug}${path.extname(group.details.picture)}`;
const filePath = path.join(groupDir, fileName);
try {
await downloadImage(group.details.picture, filePath);
} catch (e) {
console.log(`${c.red('Failed')}: ${group.details.picture}`);
}
// Update the path to the picture.
group.details.picture = path.relative(ROOT, filePath);
resolve();
}),
);
}
if (group.brands) {
for (const [brandName, brand] of group.brands.entries()) {
proms.push(
new Promise(async (resolve) => {
const fileName = `${slug(brandName)}${path.extname(brand.picture)}`;
const filePath = path.join(groupDir, fileName);
try {
await downloadImage(brand.picture, filePath);
} catch (e) {
console.log(`${c.red('Failed')}: ${brand.picture}\n${e.toString()}`);
}
// Update the path to the picture.
brand.picture = path.relative(ROOT, filePath);
group.brands.set(brandName, brand);
resolve();
}),
);
}
}
await Promise.all(proms);
return group;
};
(async () => {
try {
puppeteer.use(StealthPlugin());
const browser = await puppeteer.launch();
const page = await browser.newPage();
const proms = [];
// Get groups' configurations
const groupsPath = `${__dirname}/groups`;
for (const name of fs.readdirSync(groupsPath)) {
if (NAME && path.basename(name, path.extname(name)) !== NAME) continue;
const config = await import(`${groupsPath}/${name}`);
proms.push(scrap(page, config));
}
try {
const dataPath = path.join(ROOT, './packages/website/public/data.json');
const everything = await Promise.all(proms);
const allData = JSON.parse(await fsP.readFile(dataPath));
const groups = {};
console.log('Merging data...');
// Merge data
for (const group of everything) {
if (allData[group.details.slug]) {
allData[group.details.slug] = _.merge(allData[group.details.slug], group);
} else {
allData[group.details.slug] = group;
}
}
// Index groups by name
for (const group of [...Object.values(allData)].sort((a, b) => b.details.slug - a.details.slug)) {
// Sort brands alphabetically.
const isMap = group.brands.constructor.name === 'Map';
const brands = isMap ? Object.fromEntries(group.brands) : group.brands;
const sortedBrands = {};
for (const brandName of Object.keys(brands).sort()) {
sortedBrands[brandName] = brands[brandName];
}
groups[group.details.slug] = {
...group,
brands: sortedBrands,
};
}
console.log('Writing data...');
// Save the file in the website's assets.
await fsP.writeFile(dataPath, `${JSON.stringify(groups, null, 4)}\n`, 'utf-8');
console.log(c.green.bold(`Done.`));
} catch (e) {
console.log(c.red(`Error scrapping:\n`), e);
}
await browser.close();
} catch (e) {
console.log(c.bold.red('Root unhandled'), e);
if (browser) {
await browser.close();
}
process.exit(1);
}
})();