exporter.js 12 KB

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