exporter.js 12 KB

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