Files
wekan/models/exporter.js
T
Lauri Ojansivu 899617bd4d Greatly improved import from Trello to WeKan.
- Attachments now import. Trello attachment URLs require OAuth to download, so
  WeKan could not fetch them. The Trello import page now has two separate file
    fields: a **.json** field for a single Trello board, and a
    **.zip** field for a package produced by the
    [Trello Card Attachments Downloader](https://github.com/wekan/trello-attachments-downloader).
    The .zip may contain one *or more* board .json files together with each
    board's attachments in a board-name subfolder. The .zip is uploaded over HTTP
    and processed entirely on the server (the attachment bytes never travel over
    the realtime WebSocket, which previously overflowed the connection and made
    the page flicker): WeKan detects every board .json, matches each board to its
    attachment subfolder by name, streams each file straight into the Default
    file storage, imports all boards, then opens All Boards. The upload is guarded
    against abuse — it rejects oversized uploads, zip bombs (too many files or too
    much uncompressed data, per-file size caps) and unsafe entry paths (absolute
    paths or `..` traversal), and never overwrites existing files (stored under
    generated ids). The importer also reads attachments from `card.attachments`
    (newer Trello exports), not only from the action log, and uses the correct
    Meteor-Files insert API (the previous calls were no-ops on Meteor 3). Single
    board imports (the .json file or the pasted JSON, after the map-members step)
    now run through the same server-side HTTP path rather than the realtime
    `importBoard` method, so a heavy import can no longer drop the WebSocket and
    get retried in an endless loop (the page flickering with "Invalid frame
    header" / repeated "logged out" errors). When importing only a single board
    .json and you have saved Trello API key and token, WeKan uses them on the
    server to download that board's attachments, background image, member
    avatars and card stickers from Trello (a .json export often omits stickers;
    avatars only fill in mapped users who have none — an existing avatar is never
    overwritten); each download is best-effort and a failure never aborts the
    import. After a single-board import the new board's data is subscribed and
    loaded before opening it, so it shows its swimlanes, lists and cards
    immediately instead of needing a browser page reload (the HTTP import, unlike
    the old realtime method, does not push the written documents to the client by
    itself).
  - Import Trello-only card features: stickers (shown as Font Awesome icons on
    minicards and the card detail), card cover (color or attachment), card
    location (name, address, coordinates with an OpenStreetMap link), and the
    due-date "complete" checkbox shown on the minicard. Trello's two named
    sticker packs are renamed and highlighted (the icon keeps its normal colour)
    so they stay distinct: the "taco" pack becomes "mascot" with an underlined
    icon, and the "pete" pack becomes "computer" with a ring around the icon,
    e.g. "pete-ghost" imports as "computer ghost" with a Snapchat-ghost icon.
    Several named stickers that used to share an icon now get their own Font
    Awesome 4.7 icon (mascot active => heartbeat, pixel => qrcode, proto =>
    flask, embarrassed => meh-o, clean => bath, computer shipped => truck).
  - Live Trello API import: paste your Trello API key and token on the Trello
    import page to list all your Trello workspaces and boards, then import all
    or selected boards together with their attachments (downloaded
    server-side). Imported boards are placed under a personal workspace named
    after their Trello workspace, created by name if it does not exist, under an
    optional parent workspace you choose. The API client respects Trello's rate
    limits: it spaces out requests, honours `Retry-After` on HTTP 429, retries
    transient 5xx and network errors with capped exponential backoff, and
    reports a clear error on an invalid key/token (401). After a successful API
    import you are taken to the All Boards page where the new boards appear.
  - The live API import runs as a background job on the server: you can navigate
    away and come back to the Trello import page to watch progress, see
    per-board results, and read the full error log. Errors are shown in a
    selectable text box with a one-click "Copy to clipboard" button (and you can
    still select and copy just part of the text) so they are easy to share when
    fixing issues. If the import stops on a fatal API error (invalid token, or
    rate limit still failing after retries) you can fix the cause and Resume
    from where it left off, and a server restart leaves the job paused for
    resuming rather than lost. You can also Cancel the import, or Cancel and
    delete the boards already imported, to start the whole process over cleanly.
  - You can optionally save your Trello API key and token with the Save and
    Delete buttons on the import page. When saved, they are stored only on the
    server, never sent back to the browser, and are reused automatically when
    you list workspaces or import (so you do not have to paste them again); a
    "saved" indicator is shown, Save can overwrite them with new values, and
    Delete clears them from the database. If you do not save them, they are kept
    only in server memory for the running import and re-supplied when you resume.
  - Larger Trello JSON exports can be selected as a file instead of pasted.
  - Keep imported usernames for later mapping. Imported members that match an
    existing WeKan user (by username, or by a previously recorded imported
    username) are mapped automatically, and the imported username is remembered
    on that user so future imports map too. Members with no matching WeKan user
    are no longer lost: their usernames are kept on the board, so an admin can
    map them to real users later in Admin Panel / People (Imported Usernames),
    without having to map everyone up front at import time.
  Thanks to xet7 and Claude.
- Board background images can now be stored in WeKan. A new `backgrounds` file
  storage directory is created alongside `attachments` and `avatars` (using the
  current default storage backend), and Board menu → Board backgrounds lets a
  board admin upload background images, set one as the active board background,
  download, and delete them. Board export now includes the board's background
  images and re-imports them, and a Trello board's background image is
  downloaded and stored on import (so it keeps working even if the original
  Trello URL later changes). Thanks to xet7 and Claude.
- Stickers can be added to and removed from cards directly in WeKan, chosen from
  a set of Font Awesome icons similar to Trello's stickers (previously stickers
  only arrived via Trello import). The picker also includes every "mascot"
  (underlined) and "computer" (ringed) highlighted sticker that a Trello import
  can produce — generated from the same icon mapping the importer uses — so any
  imported sticker can also be added by hand. Stickers show on the minicard and
  in the card detail. Thanks to xet7 and Claude.
- The Trello-style "complete" checkbox (mark a card complete/incomplete,
  independent of the due date) is shown as an animated green checkbox to the
  left of the card title, both on the minicard and in the opened card, with
  "Mark as complete" / "Mark as incomplete" tooltips. It uses the same animated
  checkbox style as Admin Panel / Settings / Announcements and is vertically
  centered with the title text, and the two stay in sync. The minicard and the
  opened-card checkboxes use the same checked style (the board theme's colour, or
  green when no theme is set), so they always look identical. Subtask checkboxes
  and the card-detail custom-field checkbox now use the same animated checkbox as
  checklist items (they previously used static square icons), so every checkbox
  on a card animates consistently. Thanks to xet7 and Claude.
- Cards can now have multiple locations, similar to multiple members. The card
  detail shows a Location section (after Labels and Stickers) listing each
  location with its name, address and an OpenStreetMap link, with an "Add
  location" button to add more and a button to edit or remove each one. A single
  location imported from Trello keeps working and is shown in the same list. The
  Add/Edit location popup can also detect a location from any map link (Google
  Maps, OpenStreetMap, Bing Maps, Apple Maps, or generic `?q=`/`?ll=` links):
  paste the link, press "Detect", and the latitude, longitude and (when present)
  the place name/address are filled in automatically. The popup also has an
  "Open map links at" setting (OpenStreetMap by default, or Google/Bing/Apple
  Maps) saved to the user profile, controlling which map service the location
  "Open in map" links use. Thanks to xet7 and Claude.
- The opened card now docks to the top of the window, overlaying the global and
  board header bars, instead of opening downward from the clicked minicard, and
  it can be dragged all the way to the top without its top hiding behind those
  bars. (At 100% zoom the board wrapper no longer sets a `transform: scale(1)`,
  which had made it the containing block for the fixed card and trapped it below
  the headers.) Thanks to xet7 and Claude.

Fixes #5727,
fixes #2457,
fixes #5818,
fixes #755
2026-06-13 17:19:51 +03:00

419 lines
13 KiB
JavaScript

import { ReactiveCache } from '/imports/reactiveCache';
const Papa = require('papaparse');
import { TAPi18n } from '/imports/i18n';
import { FlowRouter } from 'meteor/ostrio:flow-router-extra';
import {
formatDateTime,
formatDate,
formatTime,
getISOWeek,
isValidDate,
isBefore,
isAfter,
isSame,
add,
subtract,
startOf,
endOf,
format,
parseDate,
now,
createDate,
fromNow,
calendar
} from '/imports/lib/dateUtils';
//const stringify = require('csv-stringify');
//const stringify = require('csv-stringify');
// exporter maybe is broken since Gridfs introduced, add fs and path
export class Exporter {
constructor(boardId, attachmentId) {
this._boardId = boardId;
this._attachmentId = attachmentId;
}
async build() {
const fs = Npm.require('fs');
const os = Npm.require('os');
const path = Npm.require('path');
const byBoard = { 'meta.boardId': this._boardId };
const byBoardNoLinked = {
boardId: this._boardId,
linkedId: { $in: ['', null] },
};
// we do not want to retrieve boardId in related elements
const noBoardId = {
fields: {
boardId: 0,
},
};
const result = {
_format: 'wekan-board-1.0.0',
};
Object.assign(
result,
await ReactiveCache.getBoard(this._boardId, {
fields: {
stars: 0,
},
}),
);
// [Old] for attachments we only export IDs and absolute url to original doc
// [New] Encode attachment to base64
const getBase64Data = function (doc, callback) {
let buffer = Buffer.allocUnsafe(0);
buffer.fill(0);
// callback has the form function (err, res) {}
const tmpFile = path.join(
os.tmpdir(),
`tmpexport${process.pid}${Math.random()}`,
);
const tmpWriteable = fs.createWriteStream(tmpFile);
const readStream = fs.createReadStream(doc.versions.original.path);
readStream.on('data', function (chunk) {
buffer = Buffer.concat([buffer, chunk]);
});
readStream.on('error', function () {
callback(null, null);
});
readStream.on('end', function () {
// done
fs.unlink(tmpFile, () => {
//ignored
});
callback(null, buffer.toString('base64'));
});
readStream.pipe(tmpWriteable);
};
const getBase64DataAsync = (doc) => new Promise((resolve, reject) => {
getBase64Data(doc, (err, res) => err ? reject(err) : resolve(res));
});
const byBoardAndAttachment = this._attachmentId
? { 'meta.boardId': this._boardId, _id: this._attachmentId }
: byBoard;
const attachmentDocs = await ReactiveCache.getAttachments(byBoardAndAttachment);
result.attachments = [];
for (const attachment of attachmentDocs) {
const filebase64 = await getBase64DataAsync(attachment);
result.attachments.push({
_id: attachment._id,
cardId: attachment.meta.cardId,
// `source` distinguishes board-level backgrounds ('board-background')
// from card attachments on import.
source: attachment.meta.source,
//url: FlowRouter.url(attachment.url()),
file: filebase64,
name: attachment.name,
type: attachment.type,
});
}
//When has a especific valid attachment return the single element
if (this._attachmentId) {
return result.attachments.length > 0 ? result.attachments[0] : {};
}
result.lists = await ReactiveCache.getLists(byBoard, noBoardId);
result.cards = await ReactiveCache.getCards(byBoardNoLinked, noBoardId);
result.swimlanes = await ReactiveCache.getSwimlanes(byBoard, noBoardId);
result.customFields = await ReactiveCache.getCustomFields(
{ boardIds: this._boardId },
{ fields: { boardIds: 0 } },
);
const cardIds = result.cards.map(card => card._id);
result.comments = await ReactiveCache.getCardComments(
{ cardId: { $in: cardIds } },
noBoardId,
);
result.activities = await ReactiveCache.getActivities(
{
$or: [{ boardId: this._boardId }, { cardId: { $in: cardIds } }],
},
noBoardId,
);
result.rules = await ReactiveCache.getRules(byBoard, noBoardId);
result.checklists = [];
result.checklistItems = [];
result.subtaskItems = [];
result.triggers = [];
result.actions = [];
for (const card of result.cards) {
result.checklists.push(
...await ReactiveCache.getChecklists({
cardId: card._id,
}),
);
result.checklistItems.push(
...await ReactiveCache.getChecklistItems({
cardId: card._id,
}),
);
result.subtaskItems.push(
...await ReactiveCache.getCards({
parentId: card._id,
}),
);
}
for (const rule of result.rules) {
result.triggers.push(
...await ReactiveCache.getTriggers(
{
_id: rule.triggerId,
},
noBoardId,
),
);
result.actions.push(
...await ReactiveCache.getActions(
{
_id: rule.actionId,
},
noBoardId,
),
);
}
// we also have to export some user data - as the other elements only
// include id but we have to be careful:
// 1- only exports users that are linked somehow to that board
// 2- do not export any sensitive information
const users = {};
result.members.forEach((member) => {
users[member.userId] = true;
});
result.lists.forEach((list) => {
users[list.userId] = true;
});
result.cards.forEach((card) => {
users[card.userId] = true;
if (card.members) {
card.members.forEach((memberId) => {
users[memberId] = true;
});
}
});
result.comments.forEach((comment) => {
users[comment.userId] = true;
});
result.activities.forEach((activity) => {
users[activity.userId] = true;
});
result.checklists.forEach((checklist) => {
users[checklist.userId] = true;
});
const byUserIds = {
_id: {
$in: Object.getOwnPropertyNames(users),
},
};
// we use whitelist to be sure we do not expose inadvertently
// some secret fields that gets added to User later.
const userFields = {
fields: {
_id: 1,
username: 1,
'profile.fullname': 1,
'profile.initials': 1,
'profile.avatarUrl': 1,
},
};
result.users = (await ReactiveCache.getUsers(byUserIds, userFields))
.map((user) => {
// user avatar is stored as a relative url, we export absolute
if ((user.profile || {}).avatarUrl) {
user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
}
return user;
});
return result;
}
async buildCsv(userDelimiter = ',', userLanguage='en') {
const result = await this.build();
const columnHeaders = [];
const cardRows = [];
const papaconfig = {
quotes: true,
quoteChar: '"',
escapeChar: '"',
delimiter: userDelimiter,
header: true,
newline: "\r\n",
skipEmptyLines: false,
escapeFormulae: true,
};
columnHeaders.push(
TAPi18n.__('title','',userLanguage),
TAPi18n.__('description','',userLanguage),
TAPi18n.__('list','',userLanguage),
TAPi18n.__('swimlane','',userLanguage),
TAPi18n.__('owner','',userLanguage),
TAPi18n.__('requested-by','',userLanguage),
TAPi18n.__('assigned-by','',userLanguage),
TAPi18n.__('members','',userLanguage),
TAPi18n.__('assignee','',userLanguage),
TAPi18n.__('labels','',userLanguage),
TAPi18n.__('card-start','',userLanguage),
TAPi18n.__('card-due','',userLanguage),
TAPi18n.__('card-end','',userLanguage),
TAPi18n.__('overtime-hours','',userLanguage),
TAPi18n.__('spent-time-hours','',userLanguage),
TAPi18n.__('createdAt','',userLanguage),
TAPi18n.__('last-modified-at','',userLanguage),
TAPi18n.__('last-activity','',userLanguage),
TAPi18n.__('voting','',userLanguage),
TAPi18n.__('archived','',userLanguage),
);
const customFieldMap = {};
let i = 0;
result.customFields.forEach((customField) => {
customFieldMap[customField._id] = {
position: i,
type: customField.type,
};
if (customField.type === 'dropdown') {
let options = '';
customField.settings.dropdownItems.forEach((item) => {
options = options === '' ? item.name : `${`${options}/${item.name}`}`;
});
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}-${options}`,
);
} else if (customField.type === 'currency') {
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}-${customField.settings.currencyCode}`,
);
} else {
columnHeaders.push(
`CustomField-${customField.name}-${customField.type}`,
);
}
i++;
});
//cardRows.push([[columnHeaders]]);
cardRows.push(columnHeaders);
result.cards.forEach((card) => {
const currentRow = [];
currentRow.push(card.title);
currentRow.push(card.description);
currentRow.push(
result.lists.find(({ _id }) => _id === card.listId).title,
);
currentRow.push(
result.swimlanes.find(({ _id }) => _id === card.swimlaneId).title,
);
currentRow.push(
result.users.find(({ _id }) => _id === card.userId).username,
);
currentRow.push(card.requestedBy ? card.requestedBy : ' ');
currentRow.push(card.assignedBy ? card.assignedBy : ' ');
let usernames = '';
card.members.forEach((memberId) => {
const user = result.users.find(({ _id }) => _id === memberId);
usernames = `${usernames + user.username} `;
});
currentRow.push(usernames.trim());
let assignees = '';
card.assignees.forEach((assigneeId) => {
const user = result.users.find(({ _id }) => _id === assigneeId);
assignees = `${assignees + user.username} `;
});
currentRow.push(assignees.trim());
let labels = '';
card.labelIds.forEach((labelId) => {
const label = result.labels.find(({ _id }) => _id === labelId);
labels = `${labels + label.name}-${label.color} `;
});
currentRow.push(labels.trim());
currentRow.push(card.startAt ? new Date(card.startAt).toISOString() : ' ');
currentRow.push(card.dueAt ? new Date(card.dueAt).toISOString() : ' ');
currentRow.push(card.endAt ? new Date(card.endAt).toISOString() : ' ');
currentRow.push(card.isOvertime ? 'true' : 'false');
currentRow.push(card.spentTime);
currentRow.push(card.createdAt ? new Date(card.createdAt).toISOString() : ' ');
currentRow.push(card.modifiedAt ? new Date(card.modifiedAt).toISOString() : ' ');
currentRow.push(
card.dateLastActivity ? new Date(card.dateLastActivity).toISOString() : ' ',
);
if (card.vote && card.vote.question !== '') {
let positiveVoters = '';
let negativeVoters = '';
card.vote.positive.forEach((userId) => {
const user = result.users.find(({ _id }) => _id === userId);
positiveVoters = `${positiveVoters + user.username} `;
});
card.vote.negative.forEach((userId) => {
const user = result.users.find(({ _id }) => _id === userId);
negativeVoters = `${negativeVoters + user.username} `;
});
const votingResult = `${
card.vote.public
? `yes-${
card.vote.positive.length
}-${positiveVoters.trimRight()}-no-${
card.vote.negative.length
}-${negativeVoters.trimRight()}`
: `yes-${card.vote.positive.length}-no-${card.vote.negative.length}`
}`;
currentRow.push(`${card.vote.question}-${votingResult}`);
} else {
currentRow.push(' ');
}
currentRow.push(card.archived ? 'true' : 'false');
//Custom fields
const customFieldValuesToPush = new Array(result.customFields.length);
card.customFields.forEach((field) => {
if (field.value !== null) {
if (customFieldMap[field._id].type === 'date') {
customFieldValuesToPush[customFieldMap[field._id].position] =
new Date(field.value).toISOString();
} else if (customFieldMap[field._id].type === 'dropdown') {
const dropdownOptions = result.customFields.find(
({ _id }) => _id === field._id,
).settings.dropdownItems;
const fieldObj = dropdownOptions.find(
({ _id }) => _id === field.value,
);
const fieldValue = (fieldObj && fieldObj.name) || null;
customFieldValuesToPush[customFieldMap[field._id].position] =
fieldValue;
} else {
customFieldValuesToPush[customFieldMap[field._id].position] =
field.value;
}
}
});
for (
let valueIndex = 0;
valueIndex < customFieldValuesToPush.length;
valueIndex++
) {
if (!(valueIndex in customFieldValuesToPush)) {
currentRow.push(' ');
} else {
currentRow.push(customFieldValuesToPush[valueIndex]);
}
}
//cardRows.push([[currentRow]]);
cardRows.push(currentRow);
});
return Papa.unparse(cardRows, papaconfig);
}
async canExport(user) {
const board = await ReactiveCache.getBoard(this._boardId);
return board && board.isVisibleBy(user);
}
}