wekanCreator.js 21 KB

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