exporter.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { ReactiveCache } from '/imports/reactiveCache';
  2. import moment from 'moment/min/moment-with-locales';
  3. const Papa = require('papaparse');
  4. import { TAPi18n } from '/imports/i18n';
  5. //const stringify = require('csv-stringify');
  6. //const stringify = require('csv-stringify');
  7. // exporter maybe is broken since Gridfs introduced, add fs and path
  8. export class Exporter {
  9. constructor(boardId, attachmentId) {
  10. this._boardId = boardId;
  11. this._attachmentId = attachmentId;
  12. }
  13. build() {
  14. const fs = Npm.require('fs');
  15. const os = Npm.require('os');
  16. const path = Npm.require('path');
  17. const byBoard = { boardId: this._boardId };
  18. const byBoardNoLinked = {
  19. boardId: this._boardId,
  20. linkedId: { $in: ['', null] },
  21. };
  22. // we do not want to retrieve boardId in related elements
  23. const noBoardId = {
  24. fields: {
  25. boardId: 0,
  26. },
  27. };
  28. const result = {
  29. _format: 'wekan-board-1.0.0',
  30. };
  31. _.extend(
  32. result,
  33. ReactiveCache.getBoard(this._boardId, {
  34. fields: {
  35. stars: 0,
  36. },
  37. }),
  38. );
  39. // [Old] for attachments we only export IDs and absolute url to original doc
  40. // [New] Encode attachment to base64
  41. const getBase64Data = function (doc, callback) {
  42. let buffer = Buffer.allocUnsafe(0);
  43. buffer.fill(0);
  44. // callback has the form function (err, res) {}
  45. const tmpFile = path.join(
  46. os.tmpdir(),
  47. `tmpexport${process.pid}${Math.random()}`,
  48. );
  49. const tmpWriteable = fs.createWriteStream(tmpFile);
  50. const readStream = doc.createReadStream();
  51. readStream.on('data', function (chunk) {
  52. buffer = Buffer.concat([buffer, chunk]);
  53. });
  54. readStream.on('error', function () {
  55. callback(null, null);
  56. });
  57. readStream.on('end', function () {
  58. // done
  59. fs.unlink(tmpFile, () => {
  60. //ignored
  61. });
  62. callback(null, buffer.toString('base64'));
  63. });
  64. readStream.pipe(tmpWriteable);
  65. };
  66. const getBase64DataSync = Meteor.wrapAsync(getBase64Data);
  67. const byBoardAndAttachment = this._attachmentId
  68. ? { boardId: this._boardId, _id: this._attachmentId }
  69. : byBoard;
  70. result.attachments = Attachments.find(byBoardAndAttachment)
  71. .fetch()
  72. .map((attachment) => {
  73. let filebase64 = null;
  74. filebase64 = getBase64DataSync(attachment);
  75. return {
  76. _id: attachment._id,
  77. cardId: attachment.meta.cardId,
  78. //url: FlowRouter.url(attachment.url()),
  79. file: filebase64,
  80. name: attachment.name,
  81. type: attachment.type,
  82. };
  83. });
  84. //When has a especific valid attachment return the single element
  85. if (this._attachmentId) {
  86. return result.attachments.length > 0 ? result.attachments[0] : {};
  87. }
  88. result.lists = Lists.find(byBoard, noBoardId).fetch();
  89. result.cards = Cards.find(byBoardNoLinked, noBoardId).fetch();
  90. result.swimlanes = Swimlanes.find(byBoard, noBoardId).fetch();
  91. result.customFields = CustomFields.find(
  92. { boardIds: this._boardId },
  93. { fields: { boardIds: 0 } },
  94. ).fetch();
  95. result.comments = CardComments.find(byBoard, noBoardId).fetch();
  96. result.activities = Activities.find(byBoard, noBoardId).fetch();
  97. result.rules = Rules.find(byBoard, noBoardId).fetch();
  98. result.checklists = [];
  99. result.checklistItems = [];
  100. result.subtaskItems = [];
  101. result.triggers = [];
  102. result.actions = [];
  103. result.cards.forEach((card) => {
  104. result.checklists.push(
  105. ...Checklists.find({
  106. cardId: card._id,
  107. }).fetch(),
  108. );
  109. result.checklistItems.push(
  110. ...ChecklistItems.find({
  111. cardId: card._id,
  112. }).fetch(),
  113. );
  114. result.subtaskItems.push(
  115. ...Cards.find({
  116. parentId: card._id,
  117. }).fetch(),
  118. );
  119. });
  120. result.rules.forEach((rule) => {
  121. result.triggers.push(
  122. ...Triggers.find(
  123. {
  124. _id: rule.triggerId,
  125. },
  126. noBoardId,
  127. ).fetch(),
  128. );
  129. result.actions.push(
  130. ...Actions.find(
  131. {
  132. _id: rule.actionId,
  133. },
  134. noBoardId,
  135. ).fetch(),
  136. );
  137. });
  138. // we also have to export some user data - as the other elements only
  139. // include id but we have to be careful:
  140. // 1- only exports users that are linked somehow to that board
  141. // 2- do not export any sensitive information
  142. const users = {};
  143. result.members.forEach((member) => {
  144. users[member.userId] = true;
  145. });
  146. result.lists.forEach((list) => {
  147. users[list.userId] = true;
  148. });
  149. result.cards.forEach((card) => {
  150. users[card.userId] = true;
  151. if (card.members) {
  152. card.members.forEach((memberId) => {
  153. users[memberId] = true;
  154. });
  155. }
  156. });
  157. result.comments.forEach((comment) => {
  158. users[comment.userId] = true;
  159. });
  160. result.activities.forEach((activity) => {
  161. users[activity.userId] = true;
  162. });
  163. result.checklists.forEach((checklist) => {
  164. users[checklist.userId] = true;
  165. });
  166. const byUserIds = {
  167. _id: {
  168. $in: Object.getOwnPropertyNames(users),
  169. },
  170. };
  171. // we use whitelist to be sure we do not expose inadvertently
  172. // some secret fields that gets added to User later.
  173. const userFields = {
  174. fields: {
  175. _id: 1,
  176. username: 1,
  177. 'profile.fullname': 1,
  178. 'profile.initials': 1,
  179. 'profile.avatarUrl': 1,
  180. },
  181. };
  182. result.users = Users.find(byUserIds, userFields)
  183. .fetch()
  184. .map((user) => {
  185. // user avatar is stored as a relative url, we export absolute
  186. if ((user.profile || {}).avatarUrl) {
  187. user.profile.avatarUrl = FlowRouter.url(user.profile.avatarUrl);
  188. }
  189. return user;
  190. });
  191. return result;
  192. }
  193. buildCsv(userDelimiter = ',', userLanguage='en') {
  194. const result = this.build();
  195. const columnHeaders = [];
  196. const cardRows = [];
  197. const papaconfig = {
  198. quotes: true,
  199. quoteChar: '"',
  200. escapeChar: '"',
  201. delimiter: userDelimiter,
  202. header: true,
  203. newline: "\r\n",
  204. skipEmptyLines: false,
  205. escapeFormulae: true,
  206. };
  207. columnHeaders.push(
  208. TAPi18n.__('title','',userLanguage),
  209. TAPi18n.__('description','',userLanguage),
  210. TAPi18n.__('list','',userLanguage),
  211. TAPi18n.__('swimlane','',userLanguage),
  212. TAPi18n.__('owner','',userLanguage),
  213. TAPi18n.__('requested-by','',userLanguage),
  214. TAPi18n.__('assigned-by','',userLanguage),
  215. TAPi18n.__('members','',userLanguage),
  216. TAPi18n.__('assignee','',userLanguage),
  217. TAPi18n.__('labels','',userLanguage),
  218. TAPi18n.__('card-start','',userLanguage),
  219. TAPi18n.__('card-due','',userLanguage),
  220. TAPi18n.__('card-end','',userLanguage),
  221. TAPi18n.__('overtime-hours','',userLanguage),
  222. TAPi18n.__('spent-time-hours','',userLanguage),
  223. TAPi18n.__('createdAt','',userLanguage),
  224. TAPi18n.__('last-modified-at','',userLanguage),
  225. TAPi18n.__('last-activity','',userLanguage),
  226. TAPi18n.__('voting','',userLanguage),
  227. TAPi18n.__('archived','',userLanguage),
  228. );
  229. const customFieldMap = {};
  230. let i = 0;
  231. result.customFields.forEach((customField) => {
  232. customFieldMap[customField._id] = {
  233. position: i,
  234. type: customField.type,
  235. };
  236. if (customField.type === 'dropdown') {
  237. let options = '';
  238. customField.settings.dropdownItems.forEach((item) => {
  239. options = options === '' ? item.name : `${`${options}/${item.name}`}`;
  240. });
  241. columnHeaders.push(
  242. `CustomField-${customField.name}-${customField.type}-${options}`,
  243. );
  244. } else if (customField.type === 'currency') {
  245. columnHeaders.push(
  246. `CustomField-${customField.name}-${customField.type}-${customField.settings.currencyCode}`,
  247. );
  248. } else {
  249. columnHeaders.push(
  250. `CustomField-${customField.name}-${customField.type}`,
  251. );
  252. }
  253. i++;
  254. });
  255. //cardRows.push([[columnHeaders]]);
  256. cardRows.push(columnHeaders);
  257. result.cards.forEach((card) => {
  258. const currentRow = [];
  259. currentRow.push(card.title);
  260. currentRow.push(card.description);
  261. currentRow.push(
  262. result.lists.find(({ _id }) => _id === card.listId).title,
  263. );
  264. currentRow.push(
  265. result.swimlanes.find(({ _id }) => _id === card.swimlaneId).title,
  266. );
  267. currentRow.push(
  268. result.users.find(({ _id }) => _id === card.userId).username,
  269. );
  270. currentRow.push(card.requestedBy ? card.requestedBy : ' ');
  271. currentRow.push(card.assignedBy ? card.assignedBy : ' ');
  272. let usernames = '';
  273. card.members.forEach((memberId) => {
  274. const user = result.users.find(({ _id }) => _id === memberId);
  275. usernames = `${usernames + user.username} `;
  276. });
  277. currentRow.push(usernames.trim());
  278. let assignees = '';
  279. card.assignees.forEach((assigneeId) => {
  280. const user = result.users.find(({ _id }) => _id === assigneeId);
  281. assignees = `${assignees + user.username} `;
  282. });
  283. currentRow.push(assignees.trim());
  284. let labels = '';
  285. card.labelIds.forEach((labelId) => {
  286. const label = result.labels.find(({ _id }) => _id === labelId);
  287. labels = `${labels + label.name}-${label.color} `;
  288. });
  289. currentRow.push(labels.trim());
  290. currentRow.push(card.startAt ? moment(card.startAt).format() : ' ');
  291. currentRow.push(card.dueAt ? moment(card.dueAt).format() : ' ');
  292. currentRow.push(card.endAt ? moment(card.endAt).format() : ' ');
  293. currentRow.push(card.isOvertime ? 'true' : 'false');
  294. currentRow.push(card.spentTime);
  295. currentRow.push(card.createdAt ? moment(card.createdAt).format() : ' ');
  296. currentRow.push(card.modifiedAt ? moment(card.modifiedAt).format() : ' ');
  297. currentRow.push(
  298. card.dateLastActivity ? moment(card.dateLastActivity).format() : ' ',
  299. );
  300. if (card.vote && card.vote.question !== '') {
  301. let positiveVoters = '';
  302. let negativeVoters = '';
  303. card.vote.positive.forEach((userId) => {
  304. const user = result.users.find(({ _id }) => _id === userId);
  305. positiveVoters = `${positiveVoters + user.username} `;
  306. });
  307. card.vote.negative.forEach((userId) => {
  308. const user = result.users.find(({ _id }) => _id === userId);
  309. negativeVoters = `${negativeVoters + user.username} `;
  310. });
  311. const votingResult = `${
  312. card.vote.public
  313. ? `yes-${
  314. card.vote.positive.length
  315. }-${positiveVoters.trimRight()}-no-${
  316. card.vote.negative.length
  317. }-${negativeVoters.trimRight()}`
  318. : `yes-${card.vote.positive.length}-no-${card.vote.negative.length}`
  319. }`;
  320. currentRow.push(`${card.vote.question}-${votingResult}`);
  321. } else {
  322. currentRow.push(' ');
  323. }
  324. currentRow.push(card.archived ? 'true' : 'false');
  325. //Custom fields
  326. const customFieldValuesToPush = new Array(result.customFields.length);
  327. card.customFields.forEach((field) => {
  328. if (field.value !== null) {
  329. if (customFieldMap[field._id].type === 'date') {
  330. customFieldValuesToPush[customFieldMap[field._id].position] =
  331. moment(field.value).format();
  332. } else if (customFieldMap[field._id].type === 'dropdown') {
  333. const dropdownOptions = result.customFields.find(
  334. ({ _id }) => _id === field._id,
  335. ).settings.dropdownItems;
  336. const fieldValue = dropdownOptions.find(
  337. ({ _id }) => _id === field.value,
  338. ).name;
  339. customFieldValuesToPush[customFieldMap[field._id].position] =
  340. fieldValue;
  341. } else {
  342. customFieldValuesToPush[customFieldMap[field._id].position] =
  343. field.value;
  344. }
  345. }
  346. });
  347. for (
  348. let valueIndex = 0;
  349. valueIndex < customFieldValuesToPush.length;
  350. valueIndex++
  351. ) {
  352. if (!(valueIndex in customFieldValuesToPush)) {
  353. currentRow.push(' ');
  354. } else {
  355. currentRow.push(customFieldValuesToPush[valueIndex]);
  356. }
  357. }
  358. //cardRows.push([[currentRow]]);
  359. cardRows.push(currentRow);
  360. });
  361. return Papa.unparse(cardRows, papaconfig);
  362. }
  363. canExport(user) {
  364. const board = ReactiveCache.getBoard(this._boardId);
  365. return board && board.isVisibleBy(user);
  366. }
  367. }