wekanCreator.js 21 KB

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