exporter.js 12 KB

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