bigbluebutton-Github/bbb-export-annotations/workers/process.js

445 lines
14 KiB
JavaScript
Raw Normal View History

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 probe from 'probe-image-size';
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';
2024-03-20 03:08:48 +08:00
import {Frame} from '../shapes/Frame.js';
2022-02-13 04:03:07 +08:00
2022-12-19 02:43:14 +08:00
const jobId = workerData.jobId;
2022-02-13 04:03:07 +08:00
const logger = new Logger('presAnn Process Worker');
const config = JSON.parse(fs.readFileSync('./config/settings.json', 'utf8'));
logger.info('Processing PDF for job ' + jobId);
2022-02-13 04:03:07 +08:00
const dropbox = path.join(config.shared.presAnnDropboxDir, jobId);
2022-12-19 02:43:14 +08:00
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;
}
/**
* 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 {void}
*/
function overlayDraw(svg, annotation) {
const drawing = new Draw(annotation);
const drawnDrawing = drawing.draw();
2022-06-08 19:02:05 +08:00
svg.add(drawnDrawing);
2022-06-15 23:49:36 +08:00
}
/**
* 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 {void}
*/
function overlayGeo(svg, annotation) {
const geo = createGeoObject(annotation);
const geoDrawn = geo.draw();
svg.add(geoDrawn);
2022-06-01 20:03:40 +08:00
}
/**
* 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 {void}
*/
function overlayHighlight(svg, annotation) {
// Adjust JSON properties
annotation.opacity = 0.3;
2022-06-14 21:33:03 +08:00
const highlight = new Highlight(annotation);
const highlightDrawn = highlight.draw();
svg.add(highlightDrawn);
2022-06-14 21:33:03 +08:00
}
/**
* 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 {void}
*/
function overlayLine(svg, annotation) {
const line = new Line(annotation);
const lineDrawn = line.draw();
svg.add(lineDrawn);
2022-06-01 01:23:24 +08:00
}
/**
* 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 {void}
*/
function overlayArrow(svg, annotation) {
const arrow = new Arrow(annotation);
const arrowDrawn = arrow.draw();
svg.add(arrowDrawn);
2022-05-25 00:35:08 +08:00
}
/**
* 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 {void}
*/
function overlaySticky(svg, annotation) {
const stickyNote = new StickyNote(annotation);
const stickyNoteDrawn = stickyNote.draw();
svg.add(stickyNoteDrawn);
2022-06-01 20:34:15 +08:00
}
/**
* 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 {void}
*/
function overlayText(svg, annotation) {
2024-03-05 20:02:01 +08:00
if (annotation?.props?.size == null || annotation?.props?.text?.length == 0) {
return;
}
2022-06-01 20:34:15 +08:00
const text = new TextShape(annotation);
const textDrawn = text.draw();
svg.add(textDrawn);
2022-05-26 00:35:43 +08:00
}
2024-03-20 03:08:48 +08:00
/**
* 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 {void}
*/
function overlayFrame(svg, annotation) {
const frameShape = new Frame(annotation);
const frame = frameShape.draw();
svg.add(frame);
}
/**
* 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 {void}
*/
2024-03-20 03:08:48 +08:00
export function overlayAnnotation(svg, annotation) {
try {
2024-03-05 20:02:01 +08:00
switch (annotation.type) {
case 'draw':
2024-03-05 20:02:01 +08:00
overlayDraw(svg, annotation);
break;
2024-03-05 20:02:01 +08:00
case 'geo':
overlayGeo(svg, annotation);
break;
2024-03-05 20:02:01 +08:00
case 'highlight':
overlayHighlight(svg, annotation);
break;
2024-03-05 20:02:01 +08:00
case 'line':
overlayLine(svg, annotation);
break;
2024-03-05 20:02:01 +08:00
case 'arrow':
overlayArrow(svg, annotation);
break;
case 'text':
2024-03-05 20:02:01 +08:00
overlayText(svg, annotation);
break;
case 'note':
overlaySticky(svg, annotation);
break;
2024-03-20 03:08:48 +08:00
case 'frame':
overlayFrame(svg, annotation);
break;
default:
2024-03-05 20:02:01 +08:00
logger.info(`Unknown annotation type ${annotation.type}.`);
logger.info(annotation);
}
} catch (error) {
2024-03-05 20:02:01 +08:00
logger.warn('Failed to overlay annotation',
{failedAnnotation: annotation, error: error});
}
2022-06-09 02:58:38 +08:00
}
/**
* 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 {void}
*/
function overlayAnnotations(svg, slideAnnotations) {
// Sort annotations by lowest child index
slideAnnotations = sortByKey(slideAnnotations, 'annotationInfo', 'index');
2024-03-20 03:08:48 +08:00
// 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);
overlayAnnotation(svg, childAnnotation.annotationInfo);
}
2022-06-09 02:58:38 +08:00
break;
2022-06-09 02:58:38 +08:00
2024-03-20 03:08:48 +08:00
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:
2024-03-20 03:08:48 +08:00
const parentId = annotation.annotationInfo.parentId;
// Don't render an annotation if it is contained in a frame.
if (!frameMap.has(parentId)) {
overlayAnnotation(svg, annotation.annotationInfo);
}
2022-02-15 23:48:58 +08:00
}
}
2022-02-15 23:48:58 +08:00
}
/**
* 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
}
});
2022-02-16 01:11:13 +08:00
await client.connect();
2022-08-24 21:31:20 +08:00
client.on('error', (err) => logger.info('Redis Client Error', err));
2022-12-19 02:43:14 +08:00
// 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(svgBackgroundSlide)) {
backgroundFormat = 'svg';
} else if (fs.existsSync(`${bgImagePath}.png`)) {
backgroundFormat = 'png';
} else if (fs.existsSync(`${bgImagePath}.jpg`)) {
backgroundFormat = 'jpg';
} else if (fs.existsSync(`${bgImagePath}.jpeg`)) {
backgroundFormat = 'jpeg';
} else {
logger.error(`Skipping slide ${currentSlide.page} (${jobId})`);
continue;
}
const dimensions = probe.sync(
fs.readFileSync(`${bgImagePath}.${backgroundFormat}`));
const slideWidth = parseInt(dimensions.width, 10);
const slideHeight = parseInt(dimensions.height, 10);
2023-03-03 20:40:23 +08:00
const maxImageWidth = config.process.maxImageWidth;
const maxImageHeight = config.process.maxImageHeight;
const ratio = Math.min(maxImageWidth / slideWidth,
maxImageHeight / slideHeight);
2023-03-03 20:40:23 +08:00
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',
});
// Add the image element
canvas
.image(`file://${dropbox}/slide${currentSlide.page}.${backgroundFormat}`)
.size(scaledWidth, scaledHeight);
// Add a group element with class 'whiteboard'
const whiteboard = canvas.group().attr({class: 'wb'});
// 4. Overlay annotations onto slides
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);
}
});
2022-12-18 03:35:24 +08:00
// Scale slide back to its original size
const convertAnnotatedSlide = [
SVGfile,
'--output-width', toPx(slideWidth),
'--output-height', toPx(slideHeight),
'-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}`);
2022-12-19 02:43:14 +08:00
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});
}
2022-05-01 05:28:11 +08:00
2024-03-05 20:02:01 +08:00
const serverFilename = exportJob.serverSideFilename.replace(/\s/g, '_');
const sanitizedServerFilename = sanitize(serverFilename);
const serverFilenameWithExtension = `${sanitizedServerFilename}.pdf`;
const mergePDFs = [
'-dNOPAUSE',
'-sDEVICE=pdfwrite',
2024-03-05 20:02:01 +08:00
`-sOUTPUTFILE="${path.join(outputDir, serverFilenameWithExtension)}"`,
`-dBATCH`].concat(ghostScriptInput);
// Resulting PDF file is stored in the presentation dir
try {
cp.spawnSync(config.shared.ghostscript, mergePDFs, {shell: false});
} catch (error) {
const errorMessage = 'GhostScript failed to merge PDFs in job' +
`${jobId}: ${error.message}`;
return logger.error(errorMessage);
}
// Launch Notifier Worker depending on job type
2024-03-05 20:02:01 +08:00
logger.info('Saved PDF at ',
`${outputDir}/${jobId}/${serverFilenameWithExtension}`);
const notifier = new WorkerStarter({
2024-03-05 20:02:01 +08:00
jobType: exportJob.jobType, jobId,
serverSideFilename: serverFilenameWithExtension,
filename: exportJob.filename});
2022-02-13 04:03:07 +08:00
notifier.notify();
await client.disconnect();
}
processPresentationAnnotations();