wekanCreator.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. const DateString = Match.Where(function (dateAsString) {
  2. check(dateAsString, String);
  3. return moment(dateAsString, moment.ISO_8601).isValid();
  4. });
  5. export class WekanCreator {
  6. constructor(data) {
  7. // we log current date, to use the same timestamp for all our actions.
  8. // this helps to retrieve all elements performed by the same import.
  9. this._nowDate = new Date();
  10. // The object creation dates, indexed by Wekan id
  11. // (so we only parse actions once!)
  12. this.createdAt = {
  13. board: null,
  14. cards: {},
  15. lists: {},
  16. };
  17. // The object creator Wekan Id, indexed by the object Wekan id
  18. // (so we only parse actions once!)
  19. this.createdBy = {
  20. cards: {}, // only cards have a field for that
  21. };
  22. // Map of labels Wekan ID => Wekan ID
  23. this.labels = {};
  24. // Map of lists Wekan ID => Wekan ID
  25. this.lists = {};
  26. // Map of cards Wekan ID => Wekan ID
  27. this.cards = {};
  28. // Map of comments Wekan ID => Wekan ID
  29. this.commentIds = {};
  30. // Map of attachments Wekan ID => Wekan ID
  31. this.attachmentIds = {};
  32. // Map of checklists Wekan ID => Wekan ID
  33. this.checklists = {};
  34. // The comments, indexed by Wekan card id (to map when importing cards)
  35. this.comments = {};
  36. // the members, indexed by Wekan member id => Wekan user ID
  37. this.members = data.membersMapping ? data.membersMapping : {};
  38. // maps a wekanCardId to an array of wekanAttachments
  39. this.attachments = {};
  40. }
  41. /**
  42. * If dateString is provided,
  43. * return the Date it represents.
  44. * If not, will return the date when it was first called.
  45. * This is useful for us, as we want all import operations to
  46. * have the exact same date for easier later retrieval.
  47. *
  48. * @param {String} dateString a properly formatted Date
  49. */
  50. _now(dateString) {
  51. if(dateString) {
  52. return new Date(dateString);
  53. }
  54. if(!this._nowDate) {
  55. this._nowDate = new Date();
  56. }
  57. return this._nowDate;
  58. }
  59. /**
  60. * if wekanUserId is provided and we have a mapping,
  61. * return it.
  62. * Otherwise return current logged user.
  63. * @param wekanUserId
  64. * @private
  65. */
  66. _user(wekanUserId) {
  67. if(wekanUserId && this.members[wekanUserId]) {
  68. return this.members[wekanUserId];
  69. }
  70. return Meteor.userId();
  71. }
  72. checkActivities(wekanActivities) {
  73. check(wekanActivities, [Match.ObjectIncluding({
  74. activityType: String,
  75. createdAt: DateString,
  76. })]);
  77. // XXX we could perform more thorough checks based on action type
  78. }
  79. checkBoard(wekanBoard) {
  80. check(wekanBoard, Match.ObjectIncluding({
  81. archived: Boolean,
  82. title: String,
  83. // XXX refine control by validating 'color' against a list of
  84. // allowed values (is it worth the maintenance?)
  85. color: String,
  86. permission: Match.Where((value) => {
  87. return ['private', 'public'].indexOf(value)>= 0;
  88. }),
  89. }));
  90. }
  91. checkCards(wekanCards) {
  92. check(wekanCards, [Match.ObjectIncluding({
  93. archived: Boolean,
  94. dateLastActivity: DateString,
  95. labelIds: [String],
  96. title: String,
  97. sort: Number,
  98. })]);
  99. }
  100. checkLabels(wekanLabels) {
  101. check(wekanLabels, [Match.ObjectIncluding({
  102. // XXX refine control by validating 'color' against a list of allowed
  103. // values (is it worth the maintenance?)
  104. color: String,
  105. })]);
  106. }
  107. checkLists(wekanLists) {
  108. check(wekanLists, [Match.ObjectIncluding({
  109. archived: Boolean,
  110. title: String,
  111. })]);
  112. }
  113. checkChecklists(wekanChecklists) {
  114. check(wekanChecklists, [Match.ObjectIncluding({
  115. cardId: String,
  116. title: String,
  117. items: [Match.ObjectIncluding({
  118. isFinished: Boolean,
  119. title: String,
  120. })],
  121. })]);
  122. }
  123. // You must call parseActions before calling this one.
  124. createBoardAndLabels(boardToImport) {
  125. const boardToCreate = {
  126. archived: boardToImport.archived,
  127. color: boardToImport.color,
  128. // very old boards won't have a creation activity so no creation date
  129. createdAt: this._now(boardToImport.createdAt),
  130. labels: [],
  131. members: [{
  132. userId: Meteor.userId(),
  133. wekanId: Meteor.userId(),
  134. isActive: true,
  135. isAdmin: true,
  136. isCommentOnly: false,
  137. swimlaneId: false,
  138. }],
  139. // Standalone Export has modifiedAt missing, adding modifiedAt to fix it
  140. modifiedAt: this._now(boardToImport.modifiedAt),
  141. permission: boardToImport.permission,
  142. slug: getSlug(boardToImport.title) || 'board',
  143. stars: 0,
  144. title: boardToImport.title,
  145. };
  146. // now add other members
  147. if(boardToImport.members) {
  148. boardToImport.members.forEach((wekanMember) => {
  149. // do we already have it in our list?
  150. if(!boardToCreate.members.some((member) => member.wekanId === wekanMember.wekanId))
  151. boardToCreate.members.push({
  152. ... wekanMember,
  153. userId: wekanMember.wekanId,
  154. });
  155. });
  156. }
  157. boardToImport.labels.forEach((label) => {
  158. const labelToCreate = {
  159. _id: Random.id(6),
  160. color: label.color,
  161. name: label.name,
  162. };
  163. // We need to remember them by Wekan ID, as this is the only ref we have
  164. // when importing cards.
  165. this.labels[label._id] = labelToCreate._id;
  166. boardToCreate.labels.push(labelToCreate);
  167. });
  168. const boardId = Boards.direct.insert(boardToCreate);
  169. Boards.direct.update(boardId, {$set: {modifiedAt: this._now()}});
  170. // log activity
  171. Activities.direct.insert({
  172. activityType: 'importBoard',
  173. boardId,
  174. createdAt: this._now(),
  175. source: {
  176. id: boardToImport.id,
  177. system: 'Wekan',
  178. },
  179. // We attribute the import to current user,
  180. // not the author from the original object.
  181. userId: this._user(),
  182. });
  183. return boardId;
  184. }
  185. /**
  186. * Create the Wekan cards corresponding to the supplied Wekan cards,
  187. * as well as all linked data: activities, comments, and attachments
  188. * @param wekanCards
  189. * @param boardId
  190. * @returns {Array}
  191. */
  192. createCards(wekanCards, boardId) {
  193. const result = [];
  194. wekanCards.forEach((card) => {
  195. const cardToCreate = {
  196. archived: card.archived,
  197. boardId,
  198. // very old boards won't have a creation activity so no creation date
  199. createdAt: this._now(this.createdAt.cards[card._id]),
  200. dateLastActivity: this._now(),
  201. description: card.description,
  202. listId: this.lists[card.listId],
  203. sort: card.sort,
  204. title: card.title,
  205. // we attribute the card to its creator if available
  206. userId: this._user(this.createdBy.cards[card._id]),
  207. dueAt: card.dueAt ? this._now(card.dueAt) : null,
  208. };
  209. // add labels
  210. if (card.labelIds) {
  211. cardToCreate.labelIds = card.labelIds.map((wekanId) => {
  212. return this.labels[wekanId];
  213. });
  214. }
  215. // add members {
  216. if(card.members) {
  217. const wekanMembers = [];
  218. // we can't just map, as some members may not have been mapped
  219. card.members.forEach((sourceMemberId) => {
  220. if(this.members[sourceMemberId]) {
  221. const wekanId = this.members[sourceMemberId];
  222. // we may map multiple Wekan members to the same wekan user
  223. // in which case we risk adding the same user multiple times
  224. if(!wekanMembers.find((wId) => wId === wekanId)){
  225. wekanMembers.push(wekanId);
  226. }
  227. }
  228. return true;
  229. });
  230. if(wekanMembers.length>0) {
  231. cardToCreate.members = wekanMembers;
  232. }
  233. }
  234. // insert card
  235. const cardId = Cards.direct.insert(cardToCreate);
  236. // keep track of Wekan id => WeKan id
  237. this.cards[card._id] = cardId;
  238. // // log activity
  239. // Activities.direct.insert({
  240. // activityType: 'importCard',
  241. // boardId,
  242. // cardId,
  243. // createdAt: this._now(),
  244. // listId: cardToCreate.listId,
  245. // source: {
  246. // id: card._id,
  247. // system: 'Wekan',
  248. // },
  249. // // we attribute the import to current user,
  250. // // not the author of the original card
  251. // userId: this._user(),
  252. // });
  253. // add comments
  254. const comments = this.comments[card._id];
  255. if (comments) {
  256. comments.forEach((comment) => {
  257. const commentToCreate = {
  258. boardId,
  259. cardId,
  260. createdAt: this._now(comment.createdAt),
  261. text: comment.text,
  262. // we attribute the comment to the original author, default to current user
  263. userId: this._user(comment.userId),
  264. };
  265. // dateLastActivity will be set from activity insert, no need to
  266. // update it ourselves
  267. const commentId = CardComments.direct.insert(commentToCreate);
  268. this.commentIds[comment._id] = commentId;
  269. // Activities.direct.insert({
  270. // activityType: 'addComment',
  271. // boardId: commentToCreate.boardId,
  272. // cardId: commentToCreate.cardId,
  273. // commentId,
  274. // createdAt: this._now(commentToCreate.createdAt),
  275. // // we attribute the addComment (not the import)
  276. // // to the original author - it is needed by some UI elements.
  277. // userId: commentToCreate.userId,
  278. // });
  279. });
  280. }
  281. const attachments = this.attachments[card._id];
  282. const wekanCoverId = card.coverId;
  283. if (attachments) {
  284. attachments.forEach((att) => {
  285. const file = new FS.File();
  286. // Simulating file.attachData on the client generates multiple errors
  287. // - HEAD returns null, which causes exception down the line
  288. // - the template then tries to display the url to the attachment which causes other errors
  289. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  290. const self = this;
  291. if(Meteor.isServer) {
  292. if (att.url) {
  293. file.attachData(att.url, function (error) {
  294. file.boardId = boardId;
  295. file.cardId = cardId;
  296. file.userId = self._user(att.userId);
  297. // The field source will only be used to prevent adding
  298. // attachments' related activities automatically
  299. file.source = 'import';
  300. if (error) {
  301. throw(error);
  302. } else {
  303. const wekanAtt = Attachments.insert(file, () => {
  304. // we do nothing
  305. });
  306. self.attachmentIds[att._id] = wekanAtt._id;
  307. //
  308. if(wekanCoverId === att._id) {
  309. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  310. }
  311. }
  312. });
  313. } else if (att.file) {
  314. file.attachData(new Buffer(att.file, 'base64'), {type: att.type}, (error) => {
  315. file.name(att.name);
  316. file.boardId = boardId;
  317. file.cardId = cardId;
  318. file.userId = self._user(att.userId);
  319. // The field source will only be used to prevent adding
  320. // attachments' related activities automatically
  321. file.source = 'import';
  322. if (error) {
  323. throw(error);
  324. } else {
  325. const wekanAtt = Attachments.insert(file, () => {
  326. // we do nothing
  327. });
  328. this.attachmentIds[att._id] = wekanAtt._id;
  329. //
  330. if(wekanCoverId === att._id) {
  331. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  332. }
  333. }
  334. });
  335. }
  336. }
  337. // todo XXX set cover - if need be
  338. });
  339. }
  340. result.push(cardId);
  341. });
  342. return result;
  343. }
  344. // Create labels if they do not exist and load this.labels.
  345. createLabels(wekanLabels, board) {
  346. wekanLabels.forEach((label) => {
  347. const color = label.color;
  348. const name = label.name;
  349. const existingLabel = board.getLabel(name, color);
  350. if (existingLabel) {
  351. this.labels[label.id] = existingLabel._id;
  352. } else {
  353. const idLabelCreated = board.pushLabel(name, color);
  354. this.labels[label.id] = idLabelCreated;
  355. }
  356. });
  357. }
  358. createLists(wekanLists, boardId) {
  359. wekanLists.forEach((list) => {
  360. const listToCreate = {
  361. archived: list.archived,
  362. boardId,
  363. // We are being defensing here by providing a default date (now) if the
  364. // creation date wasn't found on the action log. This happen on old
  365. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  366. // we require.
  367. createdAt: this._now(this.createdAt.lists[list.id]),
  368. title: list.title,
  369. };
  370. const listId = Lists.direct.insert(listToCreate);
  371. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  372. this.lists[list._id] = listId;
  373. // // log activity
  374. // Activities.direct.insert({
  375. // activityType: 'importList',
  376. // boardId,
  377. // createdAt: this._now(),
  378. // listId,
  379. // source: {
  380. // id: list._id,
  381. // system: 'Wekan',
  382. // },
  383. // // We attribute the import to current user,
  384. // // not the creator of the original object
  385. // userId: this._user(),
  386. // });
  387. });
  388. }
  389. createChecklists(wekanChecklists) {
  390. wekanChecklists.forEach((checklist, checklistIndex) => {
  391. // Create the checklist
  392. const checklistToCreate = {
  393. cardId: this.cards[checklist.cardId],
  394. title: checklist.title,
  395. createdAt: checklist.createdAt,
  396. sort: checklist.sort ? checklist.sort : checklistIndex,
  397. };
  398. const checklistId = Checklists.direct.insert(checklistToCreate);
  399. // keep track of Wekan id => WeKan id
  400. this.checklists[checklist._id] = checklistId;
  401. // Now add the items to the checklist
  402. const itemsToCreate = [];
  403. checklist.items.forEach((item, itemIndex) => {
  404. itemsToCreate.push({
  405. _id: checklistId + itemsToCreate.length,
  406. title: item.title,
  407. isFinished: item.isFinished,
  408. sort: item.sort ? item.sort : itemIndex,
  409. });
  410. });
  411. Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  412. });
  413. }
  414. parseActivities(wekanBoard) {
  415. wekanBoard.activities.forEach((activity) => {
  416. switch (activity.activityType) {
  417. case 'addAttachment': {
  418. // We have to be cautious, because the attachment could have been removed later.
  419. // In that case Wekan still reports its addition, but removes its 'url' field.
  420. // So we test for that
  421. const wekanAttachment = wekanBoard.attachments.filter((attachment) => {
  422. return attachment._id === activity.attachmentId;
  423. })[0];
  424. if(wekanAttachment.url || wekanAttachment.file) {
  425. // we cannot actually create the Wekan attachment, because we don't yet
  426. // have the cards to attach it to, so we store it in the instance variable.
  427. const wekanCardId = activity.cardId;
  428. if(!this.attachments[wekanCardId]) {
  429. this.attachments[wekanCardId] = [];
  430. }
  431. this.attachments[wekanCardId].push(wekanAttachment);
  432. }
  433. break;
  434. }
  435. case 'addComment': {
  436. const wekanComment = wekanBoard.comments.filter((comment) => {
  437. return comment._id === activity.commentId;
  438. })[0];
  439. const id = activity.cardId;
  440. if (!this.comments[id]) {
  441. this.comments[id] = [];
  442. }
  443. this.comments[id].push(wekanComment);
  444. break;
  445. }
  446. case 'createBoard': {
  447. this.createdAt.board = activity.createdAt;
  448. break;
  449. }
  450. case 'createCard': {
  451. const cardId = activity.cardId;
  452. this.createdAt.cards[cardId] = activity.createdAt;
  453. this.createdBy.cards[cardId] = activity.userId;
  454. break;
  455. }
  456. case 'createList': {
  457. const listId = activity.listId;
  458. this.createdAt.lists[listId] = activity.createdAt;
  459. break;
  460. }}
  461. });
  462. }
  463. importActivities(activities, boardId) {
  464. activities.forEach((activity) => {
  465. switch (activity.activityType) {
  466. // Board related activities
  467. // TODO: addBoardMember, removeBoardMember
  468. case 'createBoard': {
  469. Activities.direct.insert({
  470. userId: this._user(activity.userId),
  471. type: 'board',
  472. activityTypeId: boardId,
  473. activityType: activity.activityType,
  474. boardId,
  475. createdAt: this._now(activity.createdAt),
  476. });
  477. break;
  478. }
  479. // List related activities
  480. // TODO: removeList, archivedList
  481. case 'createList': {
  482. Activities.direct.insert({
  483. userId: this._user(activity.userId),
  484. type: 'list',
  485. activityType: activity.activityType,
  486. listId: this.lists[activity.listId],
  487. boardId,
  488. createdAt: this._now(activity.createdAt),
  489. });
  490. break;
  491. }
  492. // Card related activities
  493. // TODO: archivedCard, restoredCard, joinMember, unjoinMember
  494. case 'createCard': {
  495. Activities.direct.insert({
  496. userId: this._user(activity.userId),
  497. activityType: activity.activityType,
  498. listId: this.lists[activity.listId],
  499. cardId: this.cards[activity.cardId],
  500. boardId,
  501. createdAt: this._now(activity.createdAt),
  502. });
  503. break;
  504. }
  505. case 'moveCard': {
  506. Activities.direct.insert({
  507. userId: this._user(activity.userId),
  508. oldListId: this.lists[activity.oldListId],
  509. activityType: activity.activityType,
  510. listId: this.lists[activity.listId],
  511. cardId: this.cards[activity.cardId],
  512. boardId,
  513. createdAt: this._now(activity.createdAt),
  514. });
  515. break;
  516. }
  517. // Comment related activities
  518. case 'addComment': {
  519. Activities.direct.insert({
  520. userId: this._user(activity.userId),
  521. activityType: activity.activityType,
  522. cardId: this.cards[activity.cardId],
  523. commentId: this.commentIds[activity.commentId],
  524. boardId,
  525. createdAt: this._now(activity.createdAt),
  526. });
  527. break;
  528. }
  529. // Attachment related activities
  530. case 'addAttachment': {
  531. Activities.direct.insert({
  532. userId: this._user(activity.userId),
  533. type: 'card',
  534. activityType: activity.activityType,
  535. attachmentId: this.attachmentIds[activity.attachmentId],
  536. cardId: this.cards[activity.cardId],
  537. boardId,
  538. createdAt: this._now(activity.createdAt),
  539. });
  540. break;
  541. }
  542. // Checklist related activities
  543. case 'addChecklist': {
  544. Activities.direct.insert({
  545. userId: this._user(activity.userId),
  546. activityType: activity.activityType,
  547. cardId: this.cards[activity.cardId],
  548. checklistId: this.checklists[activity.checklistId],
  549. boardId,
  550. createdAt: this._now(activity.createdAt),
  551. });
  552. break;
  553. }
  554. case 'addChecklistItem': {
  555. Activities.direct.insert({
  556. userId: this._user(activity.userId),
  557. activityType: activity.activityType,
  558. cardId: this.cards[activity.cardId],
  559. checklistId: this.checklists[activity.checklistId],
  560. checklistItemId: activity.checklistItemId.replace(
  561. activity.checklistId,
  562. this.checklists[activity.checklistId]),
  563. boardId,
  564. createdAt: this._now(activity.createdAt),
  565. });
  566. break;
  567. }}
  568. });
  569. }
  570. check(board) {
  571. try {
  572. // check(data, {
  573. // membersMapping: Match.Optional(Object),
  574. // });
  575. this.checkActivities(board.activities);
  576. this.checkBoard(board);
  577. this.checkLabels(board.labels);
  578. this.checkLists(board.lists);
  579. this.checkCards(board.cards);
  580. this.checkChecklists(board.checklists);
  581. } catch (e) {
  582. throw new Meteor.Error('error-json-schema');
  583. }
  584. }
  585. create(board, currentBoardId) {
  586. // TODO : Make isSandstorm variable global
  587. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  588. Meteor.settings.public.sandstorm;
  589. if (isSandstorm && currentBoardId) {
  590. const currentBoard = Boards.findOne(currentBoardId);
  591. currentBoard.archive();
  592. }
  593. this.parseActivities(board);
  594. const boardId = this.createBoardAndLabels(board);
  595. this.createLists(board.lists, boardId);
  596. this.createCards(board.cards, boardId);
  597. this.createChecklists(board.checklists);
  598. this.importActivities(board.activities, boardId);
  599. // XXX add members
  600. return boardId;
  601. }
  602. }