Files
wekan/models/server/ExporterZip.js
T
Lauri Ojansivu b0ca226099 JSON and .zip export at every menu, streamed, from the one export popup.
Continues #1173. The board's Export menu had JSON; nothing else did, and
there was no .zip anywhere. Both are now offered wherever an export is - the
board, a swimlane, a list, a card and a checklist - from the same popup,
with the same checkboxes deciding what goes in.

They are the same export in two shapes rather than two exports. The document
is written by models/exporter.js' streaming writer either way, so a .zip's
wekan.json and a .json download of the same scope are the same bytes. What
differs is where the attachments are: base64 inside the document for JSON,
or beside it under attachments/ as the files they are for the .zip. The
"without attachments" option is now offered at every menu instead of only on
the board's.

Both halves stream. The JSON writer already wrote a document at a time from
raw cursors with backpressure; ExporterZip gives it a PassThrough that
archiver compresses as it fills, and pipes every attachment from the file
store rather than reading it into a Buffer. A board with a gigabyte of
attachments costs a gigabyte of disk reads and not a gigabyte of RAM, which
is what makes the .zip the shape to use when the JSON is too large to hold
as one string.

A scoped export is the same wekan-board-1.0.0 document with fewer rows in
it, plus the lists and swimlanes its cards refer to, so what comes out can
be imported back into somewhere. A section the popup did not tick is an
empty array rather than a missing key, for the same reason. A checklist
scope exports the card that holds it, because a checklist alone has nowhere
to land, and a swimlane export carries no board-wide rules.

Less duplication, which is the other half of this:

- every export route - JSON, .zip, PDF, Excel - reads the scope through one
  parseExportScope() and the selection through one parseExportFields(),
  instead of each picking ids out of the query itself;
- the CARD export popup IS the shared body now, with the card as its scope.
  It was its own template with its own field list, its own ReactiveDict and
  its own url builder, which is how its checkboxes came to drive the Excel
  download and not the PDF;
- one url builder serves every format and every scope, and knows that a card
  has export routes of its own so there are not two ways to ask for one
  card's PDF.

tests/boardExportScope.test.cjs gains the JSON/.zip shape, the scoped
document and the single scope parser. Two guards moved rather than being
deleted: they pinned the routes parsing their own ids and the card popup
holding its own copy of the field list.

Thanks to xet7 !
2026-08-14 00:52:48 +03:00

120 lines
5.3 KiB
JavaScript

import { PassThrough } from 'stream';
import { Exporter } from '/models/exporter';
import { fileStoreStrategyFactory } from '/models/attachments.server';
// The same export, as a .zip: the JSON beside the attachment FILES.
//
// #1173 asked for both shapes at every menu, and they are the same export twice
// over, not two exports:
//
// JSON - one document; attachments, if asked for, are base64 INSIDE it.
// .zip - the same document as `wekan.json`, and each attachment as the file
// it actually is, under `attachments/`.
//
// The document is written by models/exporter.js' `buildStream`, unchanged and
// undated, so a .zip's JSON and a .json export of the same scope are the same
// bytes. Nothing here knows what a board contains; it knows how to put a stream
// in an archive.
//
// STREAMING, both halves. `buildStream` writes into a PassThrough that archiver
// consumes as it compresses, and every attachment is piped from the file store
// rather than read into a Buffer - so a board with a gigabyte of attachments
// costs a gigabyte of disk reads and not a gigabyte of RAM. The JSON inside a
// .zip carries no base64 file data at all (`attachments` are files here), which
// is what makes the .zip the shape to use on a board too large for the .json.
class ExporterZip {
constructor(boardId, options = {}) {
this._boardId = boardId;
this._options = options;
}
async canExport(user) {
// The same check the JSON export makes, from the same place.
const { ReactiveCache } = require('/imports/reactiveCache');
const board = await ReactiveCache.getBoard(this._boardId);
return board && board.isVisibleBy(user);
}
async build(res, filename = 'export.zip') {
const archiver = require('archiver');
// store, not deflate, for the JSON? No: a board's JSON compresses to a
// fraction of itself, and the attachments are usually already-compressed
// formats where level 1 costs nothing and saves little. One level for both,
// chosen for the JSON, which is the part that is worth compressing.
const archive = archiver('zip', { zlib: { level: 6 } });
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename="${filename}"`,
});
let failed = null;
archive.on('error', err => { failed = err; });
// A warning is a file that could not be added - a deleted attachment, a
// permission problem - and is not a reason to throw away the whole export.
archive.on('warning', err => {
console.warn('ExporterZip: ', err && err.message);
});
archive.pipe(res);
// ── the document ───────────────────────────────────────────────────────
// The .zip carries the files themselves, so the JSON in it never carries
// them again as base64: `attachments` here means the metadata rows.
const jsonStream = new PassThrough();
archive.append(jsonStream, { name: 'wekan.json' });
const exporter = new Exporter(this._boardId, undefined, {
...this._options,
excludeAttachments: true,
});
const jsonDone = exporter.buildStream(jsonStream)
.then(() => jsonStream.end())
.catch(err => { jsonStream.end(); throw err; });
// ── the files ──────────────────────────────────────────────────────────
// Added while the JSON is still being written: archiver serialises the
// entries itself, and waiting would mean holding the whole document first.
const attachments = await this._attachmentsToPack();
for (const attachment of attachments) {
try {
const strategy = fileStoreStrategyFactory.getFileStrategy(attachment, 'original');
const stream = strategy && strategy.getReadStream();
if (!stream) continue;
// The id in the name is what ties the file back to its metadata row in
// wekan.json, and what stops two attachments called "photo.png" from
// being one file in the archive.
const name = (attachment.name || attachment._id).replace(/[/\\]/g, '_');
archive.append(stream, { name: `attachments/${attachment._id}-${name}` });
} catch (error) {
console.warn(`ExporterZip: could not add attachment ${attachment._id}: ${error.message}`);
}
}
await jsonDone;
await archive.finalize();
if (failed) throw failed;
}
// The attachments of what was actually exported: the whole board, or the one
// swimlane, list, card or checklist the menu asked for.
async _attachmentsToPack() {
const { ReactiveCache } = require('/imports/reactiveCache');
const exporter = new Exporter(this._boardId, undefined, this._options);
if (!exporter.hasField('attachments')) return [];
if (!exporter.hasScope()) {
return ReactiveCache.getAttachments({ 'meta.boardId': this._boardId });
}
const cardsRaw = require('/models/cards').default.rawCollection();
const selector = await exporter._scopedCardSelector(this._boardId);
const cards = await cardsRaw.find(selector, { projection: { _id: 1 } }).toArray();
const cardIds = cards.map(card => card._id);
return ReactiveCache.getAttachments({ 'meta.cardId': { $in: cardIds } });
}
}
export { ExporterZip };