forked from jgraph/draw-image-export2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport.js
621 lines (515 loc) · 15.2 KB
/
export.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
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const winston = require('winston');
const compression = require('compression');
const puppeteer = require('puppeteer');
const zlib = require('zlib');
const fetch = require('node-fetch');
const crc = require('crc');
const MAX_AREA = 15000 * 15000;
const PNG_CHUNK_IDAT = 1229209940;
var DOMParser = require('xmldom').DOMParser;
const PORT = process.env.PORT || 8000
const app = express();
//Max request size is 10 MB
app.use(bodyParser.urlencoded({ extended: false, limit: '10mb'}));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(compression({
threshold: 10,
}));
//Enable request logging using morgan and Apache combined format
app.use(morgan('combined'));
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
],
exceptionHandlers: [
new winston.transports.File({ filename: 'exceptions.log' })
]
});
//If we're not in production then log to the `console` also
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// NOTE: Key length must not be longer than 79 bytes (not checked)
function writePngWithText(origBuff, key, text, compressed, base64encoded)
{
var inOffset = 0;
var outOffset = 0;
var data = text;
var dataLen = key.length + data.length + 1; //we add 1 zeros with non-compressed data
//prepare compressed data to get its size
if (compressed)
{
data = zlib.deflateRawSync(encodeURIComponent(text));
dataLen = key.length + data.length + 2; //we add 2 zeros with compressed data
}
var outBuff = Buffer.allocUnsafe(origBuff.length + dataLen + 4); //4 is the header size "zTXt" or "tEXt"
try
{
var magic1 = origBuff.readUInt32BE(inOffset);
inOffset += 4;
var magic2 = origBuff.readUInt32BE(inOffset);
inOffset += 4;
if (magic1 != 0x89504e47 && magic2 != 0x0d0a1a0a)
{
throw new Error("PNGImageDecoder0");
}
outBuff.writeUInt32BE(magic1, outOffset);
outOffset += 4;
outBuff.writeUInt32BE(magic2, outOffset);
outOffset += 4;
}
catch (e)
{
logger.error(e.message, {stack: e.stack});
throw new Error("PNGImageDecoder1");
}
try
{
while (inOffset < origBuff.length)
{
var length = origBuff.readInt32BE(inOffset);
inOffset += 4;
var type = origBuff.readInt32BE(inOffset)
inOffset += 4;
if (type == PNG_CHUNK_IDAT)
{
// Insert zTXt chunk before IDAT chunk
outBuff.writeInt32BE(dataLen, outOffset);
outOffset += 4;
var typeSignature = (compressed) ? "zTXt" : "tEXt";
outBuff.write(typeSignature, outOffset);
outOffset += 4;
outBuff.write(key, outOffset);
outOffset += key.length;
outBuff.writeInt8(0, outOffset);
outOffset ++;
if (compressed)
{
outBuff.writeInt8(0, outOffset);
outOffset ++;
data.copy(outBuff, outOffset);
}
else
{
outBuff.write(data, outOffset);
}
outOffset += data.length;
var crcVal = crc.crc32(typeSignature);
crc.crc32(data, crcVal);
// CRC
outBuff.writeInt32BE(crcVal ^ 0xffffffff, outOffset);
outOffset += 4;
// Writes the IDAT chunk after the zTXt
outBuff.writeInt32BE(length, outOffset);
outOffset += 4;
outBuff.writeInt32BE(type, outOffset);
outOffset += 4;
origBuff.copy(outBuff, outOffset, inOffset);
// Encodes the buffer using base64 if requested
return base64encoded? outBuff.toString('base64') : outBuff;
}
outBuff.writeInt32BE(length, outOffset);
outOffset += 4;
outBuff.writeInt32BE(type, outOffset);
outOffset += 4;
origBuff.copy(outBuff, outOffset, inOffset, inOffset + length + 4);// +4 to move past the crc
inOffset += length + 4;
outOffset += length + 4;
}
}
catch (e)
{
logger.error(e.message, {stack: e.stack});
throw e;
}
}
app.post('/', handleRequest);
app.get('/', handleRequest);
async function handleRequest(req, res)
{
try
{
//Merge all parameters into body such that get and post works the same
Object.assign(req.body, req.params, req.query);
// Checks for HTML export request
if (req.body.html)
{
var html = req.body.html;
logger.info("HTML export referer: " + req.get("referer"));
var wp = req.body.w;
var w = (wp == null) ? 0 : parseInt(wp);
var hp = req.body.h;
var h = (hp == null) ? 0 : parseInt(hp);
var browser = null;
try
{
//Handles buffer constructor deprecation
if (Buffer.from && Buffer.from !== Uint8Array.from)
{
html = decodeURIComponent(
zlib.inflateRawSync(
Buffer.from(decodeURIComponent(html), 'base64')).toString());
}
else
{
html = decodeURIComponent(
zlib.inflateRawSync(
new Buffer(decodeURIComponent(html), 'base64')).toString());
}
browser = await puppeteer.launch({
headless: true,
args: ['--disable-gpu', '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
});
// Workaround for timeouts/zombies is to kill after 30 secs
setTimeout(function()
{
browser.close();
}, 30000);
const page = await browser.newPage();
await page.setContent(html, {waitUntil: "networkidle0"});
page.setViewport({width: w, height: h});
var data = await page.screenshot({
type: 'png'
});
// Cross-origin access should be allowed to now
res.header("Access-Control-Allow-Origin", "*");
res.header('Content-disposition', 'attachment; filename="capture.png"');
res.header('Content-type', 'image/png');
res.end(data);
browser.close();
}
catch (e)
{
if (browser != null)
{
browser.close();
}
logger.info("Inflate failed for HTML input: " + html);
throw e;
}
}
else
{
var xml;
if (req.body.url)
{
var urlRes = await fetch(req.body.url);
xml = await urlRes.text();
if (req.body.format == null)
req.body.format = 'png';
}
else if (req.body.xmldata)
{
try
{
xml = zlib.inflateRawSync(
new Buffer(decodeURIComponent(req.body.xmldata), 'base64')).toString();
}
catch (e)
{
logger.info("Inflate failed for XML input: " + req.body.xmldata);
throw e;
}
}
else
{
xml = req.body.xml;
}
if (xml != null && xml.indexOf("%3C") == 0)
{
xml = decodeURIComponent(xml);
}
// Extracts the compressed XML from the DIV in a HTML document
if (xml != null && (xml.indexOf("<!DOCTYPE html>") == 0
|| xml.indexOf("<!--[if IE]><meta http-equiv") == 0)) //TODO not tested!
{
try
{
var doc = new DOMParser().parseFromString(xml);
var divs = doc.documentElement
.getElementsByTagName("div");
if (divs != null && divs.length > 0
&& "mxgraph" == (divs.item(0).attributes
.getNamedItem("class").nodeValue))
{
if (divs.item(0).nodeType == 1)
{
if (divs.item(0).hasAttribute("data-mxgraph"))
{
var jsonString = divs.item(0).getAttribute("data-mxgraph");
if (jsonString != null)
{
var obj = JSON.parse(jsonString);
xml = obj["xml"];
}
}
else
{
divs = divs.item(0).getElementsByTagName("div");
if (divs != null && divs.length > 0)
{
var tmp = divs.item(0).textContent;
if (tmp != null)
{
tmp = zlib.inflateRawSync(new Buffer(tmp, 'base64')).toString();
if (tmp != null && tmp.length > 0)
{
xml = decodeURIComponent(tmp);
}
}
}
}
}
}
}
catch (e)
{
// ignore
}
}
// Extracts the URL encoded XML from the content attribute of an SVG node
if (xml != null && (xml.indexOf(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">") == 0))
{//TODO not tested!
try
{
var doc = new DOMParser().parseFromString(xml);
if (doc != null && doc.documentElement != null && doc
.documentElement.nodeName == "svg")
{
var content = doc.documentElement.getAttribute("content");
if (content != null)
{
xml = content;
if (xml.charAt(0) == '%')
{
xml = decodeURIComponent(xml);
}
}
}
}
catch (e)
{
// ignore
}
}
req.body.w = req.body.w || 0;
req.body.h = req.body.h || 0;
// Checks parameters
if (req.body.format && xml && req.body.w * req.body.h <= MAX_AREA)
{
var browser = null;
try
{
var reqStr = ((xml != null) ? "xml=" + xml.length : "")
+ ((req.body.embedXml != null) ? " embed=" + req.body.embedXml : "") + " format="
+ req.body.format;
req.body.xml = xml;
var t0 = Date.now();
browser = await puppeteer.launch({
headless: true,
args: ['--disable-gpu', '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
});
// Workaround for timeouts/zombies is to kill after 30 secs
setTimeout(function()
{
browser.close();
}, 30000);
const page = await browser.newPage();
await page.goto('https://www.draw.io/export3.html', {waitUntil: 'networkidle0'});
const result = await page.evaluate((body) => {
return render({
xml: body.xml,
format: body.format,
w: body.w,
h: body.h,
border: body.border || 0,
bg: body.bg,
"from": body["from"],
to: body.to,
pageId: body.pageId,
allPages: body.allPages,
scale: body.scale || 1,
extras: body.extras
});
}, req.body);
//default timeout is 30000 (30 sec)
await page.waitForSelector('#LoadingComplete');
var bounds = await page.mainFrame().$eval('#LoadingComplete', div => div.getAttribute('bounds'));
var pageId = await page.mainFrame().$eval('#LoadingComplete', div => div.getAttribute('page-id'));
var scale = await page.mainFrame().$eval('#LoadingComplete', div => div.getAttribute('scale'));
var pdfOptions = {format: 'A4'};
if (bounds != null)
{
bounds = JSON.parse(bounds);
//Chrome generates Pdf files larger than requested pixels size and requires scaling
var fixingScale = 0.959;
var w = Math.ceil(bounds.width * fixingScale);
// +0.1 fixes cases where adding 1px below is not enough
// Increase this if more cropped PDFs have extra empty pages
var h = Math.ceil(bounds.height * fixingScale + 0.1);
page.setViewport({width: w, height: h});
pdfOptions = {
printBackground: true,
width: w + 'px',
height: (h + 1) + 'px', //the extra pixel to prevent adding an extra empty page
margin: {top: '0px', bottom: '0px', left: '0px', right: '0px'}
}
}
// Cross-origin access should be allowed to now
res.header("Access-Control-Allow-Origin", "*");
//req.body.filename = req.body.filename || ("export." + req.body.format);
var base64encoded = req.body.base64 == "1";
if (req.body.format == 'png' || req.body.format == 'jpg' || req.body.format == 'jpeg')
{
var data = await page.screenshot({
omitBackground: req.body.format == 'png' && (req.body.bg == null || req.body.bg == 'none'),
type: req.body.format == 'jpg' ? 'jpeg' : req.body.format,
fullPage: true
});
if (req.body.embedXml == "1" && req.body.format == 'png')
{
data = writePngWithText(data, "mxGraphModel", xml, true,
base64encoded);
}
else if (req.body.embedData == "1" && req.body.format == 'png')
{
data = writePngWithText(data, req.body.dataHeader, req.body.data, true,
base64encoded);
}
else
{
if (base64encoded)
{
data = data.toString('base64');
}
if (data.length == 0)
{
throw new Error("Invalid image");
}
}
if (req.body.filename != null)
{
logger.info("Filename in request " + req.body.filename);
res.header('Content-disposition', 'attachment; filename="' + req.body.filename +
'"; filename*=UTF-8\'\'' + req.body.filename);
}
res.header('Content-type', base64encoded? 'text/plain' : ('image/' + req.body.format));
res.header("Content-Length", data.length);
// These two parameters are for Google Docs or other recipients to transfer the real image width x height information
// (in case this information is inaccessible or lost)
res.header("content-ex-width", w);
res.header("content-ex-height", h);
if (pageId != null && pageId != 'undefined')
{
res.header("content-page-id", pageId);
}
if (scale != null && scale != 'undefined')
{
res.header("content-scale", scale);
}
res.end(data);
var dt = Date.now() - t0;
logger.info("Success " + reqStr + " dt=" + dt);
}
else if (req.body.format == 'pdf')
{
var data = await page.pdf(pdfOptions);
if (req.body.filename != null)
{
res.header('Content-disposition', 'attachment; filename="' + req.body.filename +
'"; filename*=UTF-8\'\'' + req.body.filename);
}
if (base64encoded)
{
data = data.toString('base64');
}
res.header('Content-type', base64encoded? 'text/plain' : 'application/pdf');
res.header("Content-Length", data.length);
if (pageId != null && pageId != 'undefined')
{
res.header("content-page-id", pageId);
}
res.end(data);
var dt = Date.now() - t0;
logger.info("Success " + reqStr + " dt=" + dt);
}
else
{
//BAD_REQUEST
res.status(400).end("Unsupported Format!");
logger.warn("Unsupported Format: " + req.body.format);
}
await browser.close();
}
catch (e)
{
if (browser != null)
{
browser.close();
}
res.status(500).end("Error!");
var ip = (req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress).split(",")[0];
var reqStr = "ip=" + ip + " ";
if (req.body.format != null)
{
reqStr += ("format=" + req.body.format + " ");
}
if (req.body.w != null)
{
reqStr += ("w=" + req.body.w + " ");
}
if (req.body.h != null)
{
reqStr += ("h=" + req.body.h + " ");
}
if (req.body.scale != null)
{
reqStr += ("s=" + req.body.scale + " ");
}
if (req.body.bg != null)
{
reqStr += ("bg=" + req.body.bg + " ");
}
if (req.body.xmlData != null)
{
reqStr += ("xmlData=" + req.body.xmlData.length + " ");
}
logger.warn("Handled exception: " + e.message
+ " req=" + reqStr, {stack: e.stack});
}
}
else
{
res.status(400).end("BAD REQUEST");
}
//INTERNAL_SERVER_ERROR
res.status(500).end("Unknown error!");
}
}
catch(e)
{
logger.error(e.message, {stack: e.stack});
//INTERNAL_SERVER_ERROR
res.status(500).end("Unknown error");
}
};
app.listen(PORT, function ()
{
console.log(`draw.io export server listening on port ${PORT}...`);
});