wekanCreator.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. isOvertime: card.isOvertime || false,
  218. startAt: card.startAt ? this._now(card.startAt) : null,
  219. dueAt: card.dueAt ? this._now(card.dueAt) : null,
  220. spentTime: card.spentTime || null,
  221. };
  222. // add labels
  223. if (card.labelIds) {
  224. cardToCreate.labelIds = card.labelIds.map((wekanId) => {
  225. return this.labels[wekanId];
  226. });
  227. }
  228. // add members {
  229. if(card.members) {
  230. const wekanMembers = [];
  231. // we can't just map, as some members may not have been mapped
  232. card.members.forEach((sourceMemberId) => {
  233. if(this.members[sourceMemberId]) {
  234. const wekanId = this.members[sourceMemberId];
  235. // we may map multiple Wekan members to the same wekan user
  236. // in which case we risk adding the same user multiple times
  237. if(!wekanMembers.find((wId) => wId === wekanId)){
  238. wekanMembers.push(wekanId);
  239. }
  240. }
  241. return true;
  242. });
  243. if(wekanMembers.length>0) {
  244. cardToCreate.members = wekanMembers;
  245. }
  246. }
  247. // insert card
  248. const cardId = Cards.direct.insert(cardToCreate);
  249. // keep track of Wekan id => WeKan id
  250. this.cards[card._id] = cardId;
  251. // // log activity
  252. // Activities.direct.insert({
  253. // activityType: 'importCard',
  254. // boardId,
  255. // cardId,
  256. // createdAt: this._now(),
  257. // listId: cardToCreate.listId,
  258. // source: {
  259. // id: card._id,
  260. // system: 'Wekan',
  261. // },
  262. // // we attribute the import to current user,
  263. // // not the author of the original card
  264. // userId: this._user(),
  265. // });
  266. // add comments
  267. const comments = this.comments[card._id];
  268. if (comments) {
  269. comments.forEach((comment) => {
  270. const commentToCreate = {
  271. boardId,
  272. cardId,
  273. createdAt: this._now(comment.createdAt),
  274. text: comment.text,
  275. // we attribute the comment to the original author, default to current user
  276. userId: this._user(comment.userId),
  277. };
  278. // dateLastActivity will be set from activity insert, no need to
  279. // update it ourselves
  280. const commentId = CardComments.direct.insert(commentToCreate);
  281. this.commentIds[comment._id] = commentId;
  282. // Activities.direct.insert({
  283. // activityType: 'addComment',
  284. // boardId: commentToCreate.boardId,
  285. // cardId: commentToCreate.cardId,
  286. // commentId,
  287. // createdAt: this._now(commentToCreate.createdAt),
  288. // // we attribute the addComment (not the import)
  289. // // to the original author - it is needed by some UI elements.
  290. // userId: commentToCreate.userId,
  291. // });
  292. });
  293. }
  294. const attachments = this.attachments[card._id];
  295. const wekanCoverId = card.coverId;
  296. if (attachments) {
  297. attachments.forEach((att) => {
  298. const file = new FS.File();
  299. // Simulating file.attachData on the client generates multiple errors
  300. // - HEAD returns null, which causes exception down the line
  301. // - the template then tries to display the url to the attachment which causes other errors
  302. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  303. const self = this;
  304. if(Meteor.isServer) {
  305. if (att.url) {
  306. file.attachData(att.url, function (error) {
  307. file.boardId = boardId;
  308. file.cardId = cardId;
  309. file.userId = self._user(att.userId);
  310. // The field source will only be used to prevent adding
  311. // attachments' related activities automatically
  312. file.source = 'import';
  313. if (error) {
  314. throw(error);
  315. } else {
  316. const wekanAtt = Attachments.insert(file, () => {
  317. // we do nothing
  318. });
  319. self.attachmentIds[att._id] = wekanAtt._id;
  320. //
  321. if(wekanCoverId === att._id) {
  322. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  323. }
  324. }
  325. });
  326. } else if (att.file) {
  327. file.attachData(new Buffer(att.file, 'base64'), {type: att.type}, (error) => {
  328. file.name(att.name);
  329. file.boardId = boardId;
  330. file.cardId = cardId;
  331. file.userId = self._user(att.userId);
  332. // The field source will only be used to prevent adding
  333. // attachments' related activities automatically
  334. file.source = 'import';
  335. if (error) {
  336. throw(error);
  337. } else {
  338. const wekanAtt = Attachments.insert(file, () => {
  339. // we do nothing
  340. });
  341. this.attachmentIds[att._id] = wekanAtt._id;
  342. //
  343. if(wekanCoverId === att._id) {
  344. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  345. }
  346. }
  347. });
  348. }
  349. }
  350. // todo XXX set cover - if need be
  351. });
  352. }
  353. result.push(cardId);
  354. });
  355. return result;
  356. }
  357. // Create labels if they do not exist and load this.labels.
  358. createLabels(wekanLabels, board) {
  359. wekanLabels.forEach((label) => {
  360. const color = label.color;
  361. const name = label.name;
  362. const existingLabel = board.getLabel(name, color);
  363. if (existingLabel) {
  364. this.labels[label.id] = existingLabel._id;
  365. } else {
  366. const idLabelCreated = board.pushLabel(name, color);
  367. this.labels[label.id] = idLabelCreated;
  368. }
  369. });
  370. }
  371. createLists(wekanLists, boardId) {
  372. wekanLists.forEach((list) => {
  373. const listToCreate = {
  374. archived: list.archived,
  375. boardId,
  376. // We are being defensing here by providing a default date (now) if the
  377. // creation date wasn't found on the action log. This happen on old
  378. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  379. // we require.
  380. createdAt: this._now(this.createdAt.lists[list.id]),
  381. title: list.title,
  382. };
  383. const listId = Lists.direct.insert(listToCreate);
  384. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  385. this.lists[list._id] = listId;
  386. // // log activity
  387. // Activities.direct.insert({
  388. // activityType: 'importList',
  389. // boardId,
  390. // createdAt: this._now(),
  391. // listId,
  392. // source: {
  393. // id: list._id,
  394. // system: 'Wekan',
  395. // },
  396. // // We attribute the import to current user,
  397. // // not the creator of the original object
  398. // userId: this._user(),
  399. // });
  400. });
  401. }
  402. createSwimlanes(wekanSwimlanes, boardId) {
  403. wekanSwimlanes.forEach((swimlane) => {
  404. const swimlaneToCreate = {
  405. archived: swimlane.archived,
  406. boardId,
  407. // We are being defensing here by providing a default date (now) if the
  408. // creation date wasn't found on the action log. This happen on old
  409. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  410. // we require.
  411. createdAt: this._now(this.createdAt.swimlanes[swimlane._id]),
  412. title: swimlane.title,
  413. };
  414. const swimlaneId = Swimlanes.direct.insert(swimlaneToCreate);
  415. Swimlanes.direct.update(swimlaneId, {$set: {'updatedAt': this._now()}});
  416. this.swimlanes[swimlane._id] = swimlaneId;
  417. });
  418. }
  419. createChecklists(wekanChecklists) {
  420. wekanChecklists.forEach((checklist, checklistIndex) => {
  421. // Create the checklist
  422. const checklistToCreate = {
  423. cardId: this.cards[checklist.cardId],
  424. title: checklist.title,
  425. createdAt: checklist.createdAt,
  426. sort: checklist.sort ? checklist.sort : checklistIndex,
  427. };
  428. const checklistId = Checklists.direct.insert(checklistToCreate);
  429. // keep track of Wekan id => WeKan id
  430. this.checklists[checklist._id] = checklistId;
  431. // Now add the items to the checklist
  432. const itemsToCreate = [];
  433. checklist.items.forEach((item, itemIndex) => {
  434. itemsToCreate.push({
  435. _id: checklistId + itemsToCreate.length,
  436. title: item.title,
  437. isFinished: item.isFinished,
  438. sort: item.sort ? item.sort : itemIndex,
  439. });
  440. });
  441. Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  442. });
  443. }
  444. parseActivities(wekanBoard) {
  445. wekanBoard.activities.forEach((activity) => {
  446. switch (activity.activityType) {
  447. case 'addAttachment': {
  448. // We have to be cautious, because the attachment could have been removed later.
  449. // In that case Wekan still reports its addition, but removes its 'url' field.
  450. // So we test for that
  451. const wekanAttachment = wekanBoard.attachments.filter((attachment) => {
  452. return attachment._id === activity.attachmentId;
  453. })[0];
  454. if(wekanAttachment.url || wekanAttachment.file) {
  455. // we cannot actually create the Wekan attachment, because we don't yet
  456. // have the cards to attach it to, so we store it in the instance variable.
  457. const wekanCardId = activity.cardId;
  458. if(!this.attachments[wekanCardId]) {
  459. this.attachments[wekanCardId] = [];
  460. }
  461. this.attachments[wekanCardId].push(wekanAttachment);
  462. }
  463. break;
  464. }
  465. case 'addComment': {
  466. const wekanComment = wekanBoard.comments.filter((comment) => {
  467. return comment._id === activity.commentId;
  468. })[0];
  469. const id = activity.cardId;
  470. if (!this.comments[id]) {
  471. this.comments[id] = [];
  472. }
  473. this.comments[id].push(wekanComment);
  474. break;
  475. }
  476. case 'createBoard': {
  477. this.createdAt.board = activity.createdAt;
  478. break;
  479. }
  480. case 'createCard': {
  481. const cardId = activity.cardId;
  482. this.createdAt.cards[cardId] = activity.createdAt;
  483. this.createdBy.cards[cardId] = activity.userId;
  484. break;
  485. }
  486. case 'createList': {
  487. const listId = activity.listId;
  488. this.createdAt.lists[listId] = activity.createdAt;
  489. break;
  490. }
  491. case 'createSwimlane': {
  492. const swimlaneId = activity.swimlaneId;
  493. this.createdAt.swimlanes[swimlaneId] = activity.createdAt;
  494. break;
  495. }}
  496. });
  497. }
  498. importActivities(activities, boardId) {
  499. activities.forEach((activity) => {
  500. switch (activity.activityType) {
  501. // Board related activities
  502. // TODO: addBoardMember, removeBoardMember
  503. case 'createBoard': {
  504. Activities.direct.insert({
  505. userId: this._user(activity.userId),
  506. type: 'board',
  507. activityTypeId: boardId,
  508. activityType: activity.activityType,
  509. boardId,
  510. createdAt: this._now(activity.createdAt),
  511. });
  512. break;
  513. }
  514. // List related activities
  515. // TODO: removeList, archivedList
  516. case 'createList': {
  517. Activities.direct.insert({
  518. userId: this._user(activity.userId),
  519. type: 'list',
  520. activityType: activity.activityType,
  521. listId: this.lists[activity.listId],
  522. boardId,
  523. createdAt: this._now(activity.createdAt),
  524. });
  525. break;
  526. }
  527. // Card related activities
  528. // TODO: archivedCard, restoredCard, joinMember, unjoinMember
  529. case 'createCard': {
  530. Activities.direct.insert({
  531. userId: this._user(activity.userId),
  532. activityType: activity.activityType,
  533. listId: this.lists[activity.listId],
  534. cardId: this.cards[activity.cardId],
  535. boardId,
  536. createdAt: this._now(activity.createdAt),
  537. });
  538. break;
  539. }
  540. case 'moveCard': {
  541. Activities.direct.insert({
  542. userId: this._user(activity.userId),
  543. oldListId: this.lists[activity.oldListId],
  544. activityType: activity.activityType,
  545. listId: this.lists[activity.listId],
  546. cardId: this.cards[activity.cardId],
  547. boardId,
  548. createdAt: this._now(activity.createdAt),
  549. });
  550. break;
  551. }
  552. // Comment related activities
  553. case 'addComment': {
  554. Activities.direct.insert({
  555. userId: this._user(activity.userId),
  556. activityType: activity.activityType,
  557. cardId: this.cards[activity.cardId],
  558. commentId: this.commentIds[activity.commentId],
  559. boardId,
  560. createdAt: this._now(activity.createdAt),
  561. });
  562. break;
  563. }
  564. // Attachment related activities
  565. case 'addAttachment': {
  566. Activities.direct.insert({
  567. userId: this._user(activity.userId),
  568. type: 'card',
  569. activityType: activity.activityType,
  570. attachmentId: this.attachmentIds[activity.attachmentId],
  571. cardId: this.cards[activity.cardId],
  572. boardId,
  573. createdAt: this._now(activity.createdAt),
  574. });
  575. break;
  576. }
  577. // Checklist related activities
  578. case 'addChecklist': {
  579. Activities.direct.insert({
  580. userId: this._user(activity.userId),
  581. activityType: activity.activityType,
  582. cardId: this.cards[activity.cardId],
  583. checklistId: this.checklists[activity.checklistId],
  584. boardId,
  585. createdAt: this._now(activity.createdAt),
  586. });
  587. break;
  588. }
  589. case 'addChecklistItem': {
  590. Activities.direct.insert({
  591. userId: this._user(activity.userId),
  592. activityType: activity.activityType,
  593. cardId: this.cards[activity.cardId],
  594. checklistId: this.checklists[activity.checklistId],
  595. checklistItemId: activity.checklistItemId.replace(
  596. activity.checklistId,
  597. this.checklists[activity.checklistId]),
  598. boardId,
  599. createdAt: this._now(activity.createdAt),
  600. });
  601. break;
  602. }}
  603. });
  604. }
  605. check(board) {
  606. try {
  607. // check(data, {
  608. // membersMapping: Match.Optional(Object),
  609. // });
  610. this.checkActivities(board.activities);
  611. this.checkBoard(board);
  612. this.checkLabels(board.labels);
  613. this.checkLists(board.lists);
  614. this.checkSwimlanes(board.swimlanes);
  615. this.checkCards(board.cards);
  616. this.checkChecklists(board.checklists);
  617. } catch (e) {
  618. throw new Meteor.Error('error-json-schema');
  619. }
  620. }
  621. create(board, currentBoardId) {
  622. // TODO : Make isSandstorm variable global
  623. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  624. Meteor.settings.public.sandstorm;
  625. if (isSandstorm && currentBoardId) {
  626. const currentBoard = Boards.findOne(currentBoardId);
  627. currentBoard.archive();
  628. }
  629. this.parseActivities(board);
  630. const boardId = this.createBoardAndLabels(board);
  631. this.createLists(board.lists, boardId);
  632. this.createSwimlanes(board.swimlanes, boardId);
  633. this.createCards(board.cards, boardId);
  634. this.createChecklists(board.checklists);
  635. this.importActivities(board.activities, boardId);
  636. // XXX add members
  637. return boardId;
  638. }
  639. }