wekanCreator.js 20 KB

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