exporter.js 12 KB

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