/
fetch-external-images.js
158 lines (149 loc) · 4.59 KB
/
fetch-external-images.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
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const sharp = require('sharp');
const getFiles = require('./utils/get-files');
const normalizeData = require('./utils/normalize-data');
function componentToHex(c) {
const hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
function rgbToHex({ r, g, b }) {
return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
function renameKeys(content) {
return normalizeData({
obj: content,
keysMap: { href: 'url', heading: 'name' },
});
}
const downloadImage = (url, imagePath) =>
axios({
url,
responseType: 'stream',
}).then(
(response) =>
new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(imagePath))
.on('finish', () => resolve())
.on('error', (e) => reject(e));
}),
);
function checkFileExists(file) {
return fs.promises
.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
}
async function resize({ input, output }) {
try {
const buffer = await sharp(input)
.toFormat('png')
.resize({
width: 4686,
height: 2636,
fit: sharp.fit.contain,
background: { r: 255, g: 255, b: 255, alpha: 0 },
trim: true,
enlarge: true,
})
.toBuffer();
await sharp(buffer).toFile(output ?? input);
} catch (e) {
console.error(e);
}
}
async function updateContent({ folder, imageFolder }) {
// get list of urls to crawl from content files
for await (const filename of getFiles(folder)) {
const data = fs.readFileSync(filename);
const content = JSON.parse(data);
const imageUrl = content.image;
const slug = path.parse(filename).name;
const imagePath = `${imageFolder}${slug}.png`;
console.log(slug);
if (content.offers) {
for (const categoryKey in content.offers) {
const category = content.offers[categoryKey];
console.log(' - ', categoryKey);
for (const offerKey in category) {
const offer = category[offerKey];
console.log(' - ', offerKey);
const imageUrl = offer.image;
const imagePath = `${imageFolder}/offers/${slug}/${offerKey}.png`;
const fileExists = await checkFileExists(imagePath);
if (imageUrl && !fileExists) {
if (imageUrl.startsWith('http')) {
await downloadImage(imageUrl, imagePath);
} else {
await resize({ input: `static/${imageUrl}`, output: imagePath });
}
const { dominant } = await sharp(imagePath).stats();
offer.color = rgbToHex(dominant);
}
}
}
}
const fileExists = await checkFileExists(imagePath);
if (imageUrl && !fileExists) {
if (imageUrl.startsWith('http')) {
await downloadImage(imageUrl, imagePath);
await resize({ input: imagePath, output: imagePath });
} else {
await resize({ input: `static/${imageUrl}`, output: imagePath });
}
const { dominant } = await sharp(imagePath).stats();
content.color = rgbToHex(dominant);
}
const renamed = renameKeys(content);
const stringContent = JSON.stringify(renamed, null, 2) + '\n';
fs.writeFileSync(filename, stringContent);
}
}
(async () => {
const contents = [
{
slug: 'tools',
folder: 'content/tools/',
imageFolder: 'static/img/tools/',
},
{
slug: 'alternatives',
folder: 'content/alternatives/',
imageFolder: 'static/img/alternatives/',
},
];
for (const content of contents) {
console.log(content.slug);
await updateContent(content);
}
const images = [
'img/blog/best-front-end-framework.jpg',
'img/blog/docker.jpg',
'img/blog/git-workflow.png',
'img/blog/nuxt.png',
'img/blog/paperplane.jpg',
'img/blog/windows.jpg',
'img/blog.jpg',
'img/portfolio/scuber.jpg',
'https://begriffs.com/images/reorder-list.png',
];
// get list of urls to crawl from content files
for await (const image of images) {
const slug = path.parse(image).name;
const imagePath = `static/img/blog/${slug}.png`;
if (image.startsWith('http')) {
const fileExists = await checkFileExists(image);
if (!fileExists) {
await downloadImage(image, imagePath);
}
await resize({ input: imagePath, output: imagePath });
} else {
await resize({ input: `static/${image}`, output: imagePath });
}
const { dominant } = await sharp(imagePath).stats();
const hex = rgbToHex(dominant);
console.log(slug, hex);
}
})();