-
Notifications
You must be signed in to change notification settings - Fork 6
/
thumbnail.js
250 lines (227 loc) · 6.22 KB
/
thumbnail.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
/* global main */
// main is referenced here but is injected into puppeteer
'use strict';
const fs = require('fs');
const path = require('path');
const Server = require('./server');
const puppeteer = require('puppeteer');
const mime = require('mime-types');
const { createExposedPromise } = require('./lib/utils');
const logger = {
log: console.log.bind(console),
error: console.error.bind(console),
c: new Proxy({}, {
get(/*target, name*/) {
return s => s;
},
}),
};
class ServerWrapper {
constructor() {
}
async init() {
if (!this.initPromise) {
this.initPromise = new Promise((resolve, reject) => {
this.server = new Server({
local: true,
port: 8080,
scan: true,
root: __dirname,
logger: process.env.DEBUG ? logger : undefined,
});
this.server.addListener('error', reject);
this.server.addListener('start', resolve);
});
const {/*port, protocol,*/ baseUrl} = await this.initPromise;
this.baseUrl = baseUrl;
}
await this.initPromise;
}
async getBaseUrl() {
await this.init();
return this.baseUrl;
}
async addFile(pathname, mimeType, content) {
await this.init();
this.server.addFile(pathname, mimeType, content);
}
async deleteFile(pathname) {
await this.init();
this.server.deleteFile(pathname);
}
async deleteFiles() {
// TDB
}
async close() {
if (this.initPromise) {
delete this.initPromise;
const {server} = this;
this.server = undefined;
const p = new Promise((resolve) => {
server.addListener('close', resolve);
});
server.close();
await p;
}
}
}
function readFileAsBuffer(filename) {
return fs.readFileSync(filename);
}
// const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
class ThumbnailGenerator {
constructor() {
this.id = 0;
}
async launch(settings) {
if (this.initPromise) {
return this.initPromise.promise;
}
this.initPromise = createExposedPromise();
this.browser = await puppeteer.launch({
dumpio: !!process.env.DEBUG,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
],
});
this.page = await this.browser.newPage();
/*
this.page.on('console', message =>
console.log(`===========> ${message.type().substr(0, 3).toUpperCase()} ${message.text()}`));
this.page.on('pageerror', ({ message }) => console.log('=-=-=-=-=>', message));
*/
this.server = new ServerWrapper();
await this.server.init();
const {server, page} = this;
const promises = [
server.getBaseUrl(),
];
const js = readFileAsBuffer(require.resolve('@gfxfundamentals/thumbnail-gen'));
promises.push(server.addFile('thumbnail-gen.js', 'application/javascript', js));
const userFonts = settings.fonts || [];
const fonts = [
// default font
{ name: 'lesson-font', filename: path.join(__dirname, 'fonts', 'KlokanTechNotoSansCJK-Bold.otf'), },
...userFonts,
];
const fontsHTML = fonts.map(({name, filename}, ndx) => {
const font = readFileAsBuffer(filename);
const refName = `fonts/font-${ndx}${path.extname(filename)}`;
promises.push(server.addFile(refName, mime.lookup(filename), font));
// we need to put usage of each font otherwise
return `
<style>
@font-face {
font-family: "${name}";
src: url("${refName}");
}
</style>
<div style="font-family: ${name};">test</div>
`;
});
const id = '00000';
const img = readFileAsBuffer(settings.backgroundFilename);
const ext = path.extname(settings.backgroundFilename);
const imgFilename = `img-${id}${ext}`;
const imgMimeType = mime.lookup(settings.backgroundFilename);
promises.push(server.addFile(imgFilename, imgMimeType, img));
const html = `
<body>
${fontsHTML.join('\n')}
</body>
<script src="thumbnail-gen.js"></script>
<script>
'use strict';
const imgs = new Map();
async function loadImage(src) {
return new Promise((resolve, reject) => {
let img = imgs.get(src);
if (img) {
resolve(img);
return;
}
img = new Image();
imgs.set(src, img);
img.onload = () => resolve(img);
img.onerror = reject;
img.src = src;
});
}
function createExposedPromise() {
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return {
promise,
resolve,
reject,
};
}
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
async function main(settings) {
try {
await document.fonts.ready;
const logo = await loadImage(settings.imgFilename);
canvas.width = logo.width;
canvas.height = logo.height;
settings.backgroundImage = logo;
settings.canvas = canvas;
genThumbnail(settings);
return canvas;
} catch(e) {
console.error(e);
throw e;
}
}
</script>
`;
const htmlFilename = `page-${id}.html`;
promises.push(server.addFile(htmlFilename, 'text/html', html));
const results = await Promise.all(promises);
const baseUrl = results[0];
const htmlHref = `${baseUrl}/${htmlFilename}`;
await page.goto(htmlHref, {
waitUntil: 'networkidle2',
});
// these should be put in a cache
this.imgHref = `${baseUrl}/${imgFilename}`;
this.initPromise.resolve();
return this.initPromise.promise;
}
async generate(_settings) {
await this.launch(_settings);
const settings = {
..._settings,
imgFilename: this.imgHref,
};
const {page} = this;
const data = await page.evaluate(async(settings) => {
const canvas = await main(settings);
return {
dataURL: canvas.toDataURL('image/jpeg', 0.9),
};
}, settings);
const header = 'data:image/jpeg;base64,';
const bytes = Buffer.from(data.dataURL.substring(header.length), 'base64');
return bytes;
}
async close() {
if (this.browser) {
const {browser, server} = this;
delete this.browser;
delete this.page;
delete this.server;
await Promise.all([
server.deleteFiles,
]);
await browser.close();
await server.close();
}
}
}
module.exports = ThumbnailGenerator;