wekanCreator.js 22 KB

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