forked from bigbluebutton/bigbluebutton
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.js
More file actions
528 lines (465 loc) · 17 KB
/
Copy pathprocess.js
File metadata and controls
528 lines (465 loc) · 17 KB
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
import Logger from '../lib/utils/logger.js';
import fs from 'fs';
import {createSVGWindow} from 'svgdom';
import {SVG as svgCanvas, registerWindow} from '@svgdotjs/svg.js';
import cp from 'child_process';
import WorkerStarter from '../lib/utils/worker-starter.js';
import {workerData} from 'worker_threads';
import path from 'path';
import sanitize from 'sanitize-filename';
import redis from 'redis';
import {PresAnnStatusMsg} from '../lib/utils/message-builder.js';
import {sortByKey} from '../shapes/helpers.js';
import {Draw} from '../shapes/Draw.js';
import {Highlight} from '../shapes/Highlight.js';
import {Line} from '../shapes/Line.js';
import {Arrow} from '../shapes/Arrow.js';
import {TextShape} from '../shapes/TextShape.js';
import {StickyNote} from '../shapes/StickyNote.js';
import {createGeoObject} from '../shapes/geoFactory.js';
import {Frame} from '../shapes/Frame.js';
import {Poll} from '../shapes/Poll.js';
const jobId = workerData.jobId;
const logger = new Logger('presAnn Process Worker');
const config = JSON.parse(fs.readFileSync('./config/settings.json', 'utf8'));
logger.info('Processing PDF for job ' + jobId);
const dropbox = path.join(config.shared.presAnnDropboxDir, jobId);
const job = fs.readFileSync(path.join(dropbox, 'job'));
const exportJob = JSON.parse(job);
const statusUpdate = new PresAnnStatusMsg(exportJob,
PresAnnStatusMsg.EXPORT_STATUSES.PROCESSING);
/**
* Converts measured points to pixels, using the predefined points-per-inch
* and pixels-per-inch ratios from the configuration.
*
* @function toPx
* @param {number} pt - The measurement in points to be converted.
* @return {number} The converted measurement in pixels.
*/
function toPx(pt) {
return (pt / config.process.pointsPerInch) * config.process.pixelsPerInch;
}
/**
* Returns the MIME type for a supported slide background format.
*
* @param {string} backgroundFormat - The slide background file extension.
* @return {string} The MIME type for the background image.
*/
function getBackgroundMimeType(backgroundFormat) {
switch (backgroundFormat) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'svg':
return 'image/svg+xml';
default:
return 'application/octet-stream';
}
}
/**
* Builds a data URI for a slide background.
*
* Embedding the background avoids CairoSVG external file access restrictions,
* while keeping the conversion compatible with older CairoSVG versions.
*
* @param {string} backgroundFile - Absolute path to the background file.
* @param {string} backgroundFormat - The slide background file extension.
* @return {string} A data URI containing the background image.
*/
function getBackgroundDataURI(backgroundFile, backgroundFormat) {
const mimeType = getBackgroundMimeType(backgroundFormat);
const backgroundData = fs.readFileSync(backgroundFile).toString('base64');
return `data:${mimeType};base64,${backgroundData}`;
}
/**
* Creates a new drawing instance from the provided annotation
* and then adds the resulting drawn element to the SVG.
*
* @function overlayDraw
* @param {Object} svg - The SVG element to which the drawing will be added.
* @param {Object} annotation - The annotation data used to create the drawing.
* @return {Promise<void>}
*/
async function overlayDraw(svg, annotation) {
const drawing = new Draw(annotation);
const drawnDrawing = await drawing.draw();
svg.add(drawnDrawing);
}
/**
* Creates a geometric object from the annotation and then adds
* the rendered shape to the SVG.
* @function overlayGeo
* @param {Object} svg - SVG element to which the geometric shape will be added.
* @param {Object} annotation - Annotation data used to create the geo shape.
* @return {Promise<void>}
*/
async function overlayGeo(svg, annotation) {
const geo = createGeoObject(annotation);
const geoDrawn = await geo.draw();
svg.add(geoDrawn);
}
/**
* Applies a highlight effect to an SVG element using the provided annotation.
* Adjusts the annotation's opacity and draws the highlight.
* @function overlayHighlight
* @param {Object} svg - SVG element to which the highlight will be applied.
* @param {Object} annotation - JSON annotation data.
* @return {Promise<void>}
*/
async function overlayHighlight(svg, annotation) {
// Adjust JSON properties
annotation.opacity = 0.3;
const highlight = new Highlight(annotation);
const highlightDrawn = await highlight.draw();
svg.add(highlightDrawn);
}
/**
* Adds a line to an SVG element based on the provided annotation.
* It creates a line object from the annotation and then adds
* the rendered line to the SVG.
* @function overlayLine
* @param {Object} svg - SVG element to which the line will be added.
* @param {Object} annotation - JSON annotation data for the line.
* @return {Promise<void>}
*/
async function overlayLine(svg, annotation) {
const line = new Line(annotation);
const lineDrawn = await line.draw();
svg.add(lineDrawn);
}
/**
* Adds an arrow to an SVG element using the provided annotation data.
* It constructs an arrow object and then appends the drawn arrow to the SVG.
* @function overlayArrow
* @param {Object} svg - The SVG element where the arrow will be added.
* @param {Object} annotation - JSON annotation data for the arrow.
* @return {Promise<void>}
*/
async function overlayArrow(svg, annotation) {
const arrow = new Arrow(annotation);
const arrowDrawn = await arrow.draw();
svg.add(arrowDrawn);
}
/**
* Overlays a sticky note onto an SVG element based on the given annotation.
* Creates a sticky note instance and then appends the rendered note to the SVG.
* @function overlaySticky
* @param {Object} svg - SVG element to which the sticky note will be added.
* @param {Object} annotation - JSON annotation data for the sticky note.
* @return {Promise<void>}
*/
async function overlaySticky(svg, annotation) {
const stickyNote = new StickyNote(annotation);
const stickyNoteDrawn = await stickyNote.draw();
svg.add(stickyNoteDrawn);
}
/**
* Overlays text onto an SVG element using the provided annotation data.
* Initializes a text shape object with the annotation and then adds
* the rendered text to the SVG.
* @function overlayText
* @param {Object} svg - The SVG element where the text will be added.
* @param {Object} annotation - JSON annotation data for the text.
* @return {Promise<void>}
*/
async function overlayText(svg, annotation) {
if (annotation?.props?.size == null || annotation?.props?.text?.length == 0) {
return;
}
const text = new TextShape(annotation);
const textDrawn = await text.draw();
svg.add(textDrawn);
}
/**
* Adds a frame shape to the canvas.
* @function overlayText
* @param {Object} svg - The SVG element where the frame will be added.
* @param {Object} annotation - JSON frame data.
* @return {Promise<void>}
*/
async function overlayFrame(svg, annotation) {
const frameShape = new Frame(annotation);
const frame = await frameShape.draw();
svg.add(frame);
}
/**
* Adds a poll shape to the canvas.
* @function overlayPoll
* @param {Object} svg - The SVG element where the poll will be added.
* @param {Object} annotation - JSON poll data.
* @return {Promise<void>}
*/
async function overlayPoll(svg, annotation) {
const pollShape = new Poll(annotation);
const poll = await pollShape.draw();
svg.add(poll);
}
/**
* Determines the annotation type and overlays the corresponding shape
* onto the SVG element. It delegates the rendering to the specific
* overlay function based on the annotation type.
* @function overlayAnnotation
* @param {Object} svg - SVG element onto which the annotation will be overlaid.
* @param {Object} annotation - JSON annotation data.
* @return {Promise<void>}
*/
export async function overlayAnnotation(svg, annotation) {
try {
switch (annotation.type) {
case 'draw':
await overlayDraw(svg, annotation);
break;
case 'geo':
await overlayGeo(svg, annotation);
break;
case 'highlight':
await overlayHighlight(svg, annotation);
break;
case 'line':
await overlayLine(svg, annotation);
break;
case 'arrow':
await overlayArrow(svg, annotation);
break;
case 'text':
await overlayText(svg, annotation);
break;
case 'note':
await overlaySticky(svg, annotation);
break;
case 'frame':
await overlayFrame(svg, annotation);
break;
case 'poll':
await overlayPoll(svg, annotation);
break;
default:
logger.info(`Unknown annotation type ${annotation.type}.`);
logger.info(annotation);
}
} catch (error) {
logger.warn('Failed to overlay annotation',
{failedAnnotation: annotation, error: error});
}
}
/**
* Overlays a collection of annotations onto an SVG element.
* It sorts the annotations by their index before overlaying them to maintain
* the stacking order.
* @function overlayAnnotations
* @param {Object} svg - SVG element onto which annotations will be overlaid.
* @param {Array} slideAnnotations - Array of JSON annotation data objects.
* @return {Promise<void>}
*/
async function overlayAnnotations(svg, slideAnnotations) {
// Sort annotations by lowest child index
slideAnnotations = sortByKey(slideAnnotations, 'annotationInfo', 'index');
// Map to store frames and their children
const frameMap = new Map();
// First pass to identify frames and initialize them in the map
slideAnnotations.forEach((ann) => {
if (ann.annotationInfo.type === 'frame') {
frameMap.set(
ann.annotationInfo.id,
{children: []});
}
});
// Second pass to add children to the frames
slideAnnotations.forEach((child) => {
// Get the parent of this annotation
const parentId = child.annotationInfo.parentId;
// Check if the annotation is in a frame.
if (frameMap.has(parentId)) {
const frame = frameMap.get(parentId);
frame.children.push(child.annotationInfo);
}
});
for (const annotation of slideAnnotations) {
switch (annotation.annotationInfo.type) {
case 'group':
// Get annotations that have this group as parent
for (const childId of annotation.annotationInfo.children) {
const childAnnotation =
slideAnnotations.find((ann) => ann.id == childId);
await overlayAnnotation(svg, childAnnotation.annotationInfo);
}
break;
case 'frame':
const annotationId = annotation.annotationInfo.id;
// Add children to this frame
annotation.annotationInfo.children =
frameMap.get(annotationId).children;
// Intentionally fall through to default case
default:
const parentId = annotation.annotationInfo.parentId;
// Don't render an annotation if it is contained in a frame.
if (!frameMap.has(parentId)) {
await overlayAnnotation(svg, annotation.annotationInfo);
}
}
}
}
/**
* Processes presentation slides and associated annotations into
* a single PDF file.
* @async
* @function processPresentationAnnotations
* @return {Promise<void>} A promise that resolves when the process is complete.
*/
async function processPresentationAnnotations() {
const client = redis.createClient({
password: config.redis.password,
socket: {
host: config.redis.host,
port: config.redis.port,
},
});
await client.connect();
client.on('error', (err) => logger.info('Redis Client Error', err));
// Get the annotations
const annotations = fs.readFileSync(path.join(dropbox, 'whiteboard'));
const whiteboardJSON = JSON.parse(annotations);
const pages = JSON.parse(whiteboardJSON.pages);
const ghostScriptInput = [];
for (const currentSlide of pages) {
const bgImagePath = path.join(dropbox, `slide${currentSlide.page}`);
const svgBackgroundSlide = path.join(
exportJob.presLocation,
'svgs',
`slide${currentSlide.page}.svg`);
let backgroundFormat = '';
if (fs.existsSync(`${bgImagePath}.png`)) {
backgroundFormat = 'png';
} else if (fs.existsSync(`${bgImagePath}.jpg`)) {
backgroundFormat = 'jpg';
} else if (fs.existsSync(`${bgImagePath}.jpeg`)) {
backgroundFormat = 'jpeg';
} else if (fs.existsSync(svgBackgroundSlide)) {
backgroundFormat = 'svg';
} else {
logger.error(
`Skipping slide ${currentSlide.page} (${jobId}): unknown extension`,
);
continue;
}
// Rescale slide width and height to match tldraw coordinates
const slideWidth = currentSlide.width;
const slideHeight = currentSlide.height;
if (!slideWidth || !slideHeight) {
logger.error(
`Skipping slide ${currentSlide.page} (${jobId}): unknown dimensions`,
);
continue;
}
const maxImageWidth = config.process.maxImageWidth;
const maxImageHeight = config.process.maxImageHeight;
const ratio = Math.min(maxImageWidth / slideWidth,
maxImageHeight / slideHeight);
const scaledWidth = slideWidth * ratio;
const scaledHeight = slideHeight * ratio;
// Create a window with a document and an SVG root node
const window = createSVGWindow();
const document = window.document;
// Register window and document
registerWindow(window, document);
// Create the canvas (root SVG element)
const canvas = svgCanvas(document.documentElement)
.size(scaledWidth, scaledHeight)
.attr({
'xmlns': 'http://www.w3.org/2000/svg',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
});
const backgroundFile = path.join(dropbox,
`slide${currentSlide.page}.${backgroundFormat}`);
const backgroundDataURI = getBackgroundDataURI(backgroundFile,
backgroundFormat);
// Add the image element
canvas
.image(backgroundDataURI)
.size(scaledWidth, scaledHeight);
// Add a group element with class 'whiteboard'
const whiteboard = canvas.group().attr({class: 'wb'});
// 4. Overlay annotations onto slides
await overlayAnnotations(whiteboard, currentSlide.annotations);
const svg = canvas.svg();
// Write annotated SVG file
const SVGfile = path.join(dropbox,
`annotated-slide${currentSlide.page}.svg`);
const PDFfile = path.join(dropbox,
`annotated-slide${currentSlide.page}.pdf`);
fs.writeFileSync(SVGfile, svg, function(err) {
if (err) {
return logger.error(err);
}
});
/**
* Constructs the command arguments for converting an annotated slide from
* SVG to PDF format.
*
* `cairoSVGUnsafeFlag` should be enabled (true) for CairoSVG
* versions >= 2.7.0 to allow external resources, such as presentation
* slides, to be loaded.
*
* @const {string[]} convertAnnotatedSlide - The command arguments for the
* conversion process.
*/
const convertAnnotatedSlide = [
SVGfile,
'--output-width', toPx(slideWidth),
'--output-height', toPx(slideHeight),
...(config.process.cairoSVGUnsafeFlag ? ['-u'] : []),
'-o', PDFfile,
];
try {
cp.spawnSync(config.shared.cairosvg,
convertAnnotatedSlide, {shell: false});
} catch (error) {
logger.error(`Processing slide ${currentSlide.page}
failed for job ${jobId}: ${error.message}`);
statusUpdate.setError();
}
await client.publish(config.redis.channels.publish,
statusUpdate.build(currentSlide.page));
ghostScriptInput.push(PDFfile);
}
const outputDir = path.join(exportJob.presLocation, 'pdfs', jobId);
// Create PDF output directory if it doesn't exist
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, {recursive: true});
}
const serverFilename = exportJob.serverSideFilename.replace(/\s/g, '_');
const sanitizedServerFilename = sanitize(serverFilename);
const serverFilenameWithExtension = `${sanitizedServerFilename}.pdf`;
const mergePDFs = [
'-dNOPAUSE',
'-dAutoRotatePages=/None',
'-sDEVICE=pdfwrite',
`-sOUTPUTFILE=${path.join(outputDir, serverFilenameWithExtension)}`,
'-dBATCH'].concat(ghostScriptInput);
// Resulting PDF file is stored in the presentation dir
const outputFile = path.join(outputDir, serverFilenameWithExtension);
const result = cp.spawnSync(config.shared.ghostscript, mergePDFs,
{shell: false});
if (result.error || result.status !== 0 || !fs.existsSync(outputFile)) {
const errorMessage = result.error?.message ||
result.stderr?.toString() ||
`GhostScript exited with status ${result.status}`;
statusUpdate.setError();
await client.publish(config.redis.channels.publish,
statusUpdate.build());
await client.disconnect();
return logger.error(`GhostScript failed to merge PDFs in job ${jobId}: ` +
errorMessage);
}
// Launch Notifier Worker depending on job type
logger.info('Saved PDF at ', outputFile);
const notifier = new WorkerStarter({
jobType: exportJob.jobType, jobId,
serverSideFilename: serverFilenameWithExtension,
filename: exportJob.filename});
notifier.notify();
await client.disconnect();
}
processPresentationAnnotations();