wekanCreator.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. // The comments, indexed by Wekan card id (to map when importing cards)
  29. this.comments = {};
  30. // the members, indexed by Wekan member id => Wekan user ID
  31. this.members = data.membersMapping ? data.membersMapping : {};
  32. // maps a wekanCardId to an array of wekanAttachments
  33. this.attachments = {};
  34. }
  35. /**
  36. * If dateString is provided,
  37. * return the Date it represents.
  38. * If not, will return the date when it was first called.
  39. * This is useful for us, as we want all import operations to
  40. * have the exact same date for easier later retrieval.
  41. *
  42. * @param {String} dateString a properly formatted Date
  43. */
  44. _now(dateString) {
  45. if(dateString) {
  46. return new Date(dateString);
  47. }
  48. if(!this._nowDate) {
  49. this._nowDate = new Date();
  50. }
  51. return this._nowDate;
  52. }
  53. /**
  54. * if wekanUserId is provided and we have a mapping,
  55. * return it.
  56. * Otherwise return current logged user.
  57. * @param wekanUserId
  58. * @private
  59. */
  60. _user(wekanUserId) {
  61. if(wekanUserId && this.members[wekanUserId]) {
  62. return this.members[wekanUserId];
  63. }
  64. return Meteor.userId();
  65. }
  66. checkActivities(wekanActivities) {
  67. check(wekanActivities, [Match.ObjectIncluding({
  68. userId: String,
  69. activityType: String,
  70. createdAt: DateString,
  71. })]);
  72. // XXX we could perform more thorough checks based on action type
  73. }
  74. checkBoard(wekanBoard) {
  75. check(wekanBoard, Match.ObjectIncluding({
  76. archived: Boolean,
  77. title: String,
  78. // XXX refine control by validating 'color' against a list of
  79. // allowed values (is it worth the maintenance?)
  80. color: String,
  81. permission: Match.Where((value) => {
  82. return ['private', 'public'].indexOf(value)>= 0;
  83. }),
  84. }));
  85. }
  86. checkCards(wekanCards) {
  87. check(wekanCards, [Match.ObjectIncluding({
  88. archived: Boolean,
  89. dateLastActivity: DateString,
  90. labelIds: [String],
  91. members: [String],
  92. title: String,
  93. sort: Number,
  94. })]);
  95. }
  96. checkLabels(wekanLabels) {
  97. check(wekanLabels, [Match.ObjectIncluding({
  98. // XXX refine control by validating 'color' against a list of allowed
  99. // values (is it worth the maintenance?)
  100. color: String,
  101. name: String,
  102. })]);
  103. }
  104. checkLists(wekanLists) {
  105. check(wekanLists, [Match.ObjectIncluding({
  106. archived: Boolean,
  107. title: String,
  108. })]);
  109. }
  110. // checkChecklists(wekanChecklists) {
  111. // check(wekanChecklists, [Match.ObjectIncluding({
  112. // idBoard: String,
  113. // idCard: String,
  114. // name: String,
  115. // checkItems: [Match.ObjectIncluding({
  116. // state: String,
  117. // name: String,
  118. // })],
  119. // })]);
  120. // }
  121. // You must call parseActions before calling this one.
  122. createBoardAndLabels(wekanBoard) {
  123. const boardToCreate = {
  124. archived: wekanBoard.archived,
  125. color: wekanBoard.color,
  126. // very old boards won't have a creation activity so no creation date
  127. createdAt: this._now(wekanBoard.createdAt),
  128. labels: [],
  129. members: [{
  130. userId: Meteor.userId(),
  131. isAdmin: true,
  132. isActive: true,
  133. isCommentOnly: false,
  134. }],
  135. permission: wekanBoard.permission,
  136. slug: getSlug(wekanBoard.title) || 'board',
  137. stars: 0,
  138. title: wekanBoard.title,
  139. };
  140. // now add other members
  141. if(wekanBoard.members) {
  142. wekanBoard.members.forEach((wekanMember) => {
  143. const wekanId = wekanMember.userId;
  144. // do we have a mapping?
  145. if(this.members[wekanId]) {
  146. const wekanId = this.members[wekanId];
  147. // do we already have it in our list?
  148. const wekanMember = boardToCreate.members.find((wekanMember) => wekanMember.userId === wekanId);
  149. if(!wekanMember) {
  150. boardToCreate.members.push({
  151. userId: wekanId,
  152. isAdmin: wekanMember.isAdmin,
  153. isActive: true,
  154. isCommentOnly: false,
  155. });
  156. }
  157. }
  158. });
  159. }
  160. wekanBoard.labels.forEach((label) => {
  161. const labelToCreate = {
  162. _id: Random.id(6),
  163. color: label.color,
  164. name: label.name,
  165. };
  166. // We need to remember them by Wekan ID, as this is the only ref we have
  167. // when importing cards.
  168. this.labels[label._id] = labelToCreate._id;
  169. boardToCreate.labels.push(labelToCreate);
  170. });
  171. const boardId = Boards.direct.insert(boardToCreate);
  172. Boards.direct.update(boardId, {$set: {modifiedAt: this._now()}});
  173. // log activity
  174. Activities.direct.insert({
  175. activityType: 'importBoard',
  176. boardId,
  177. createdAt: this._now(),
  178. source: {
  179. id: wekanBoard.id,
  180. system: 'Wekan',
  181. },
  182. // We attribute the import to current user,
  183. // not the author from the original object.
  184. userId: this._user(),
  185. });
  186. return boardId;
  187. }
  188. /**
  189. * Create the Wekan cards corresponding to the supplied Wekan cards,
  190. * as well as all linked data: activities, comments, and attachments
  191. * @param wekanCards
  192. * @param boardId
  193. * @returns {Array}
  194. */
  195. createCards(wekanCards, boardId) {
  196. const result = [];
  197. wekanCards.forEach((card) => {
  198. const cardToCreate = {
  199. archived: card.archived,
  200. boardId,
  201. // very old boards won't have a creation activity so no creation date
  202. createdAt: this._now(this.createdAt.cards[card._id]),
  203. dateLastActivity: this._now(),
  204. description: card.description,
  205. listId: this.lists[card.listId],
  206. sort: card.sort,
  207. title: card.title,
  208. // we attribute the card to its creator if available
  209. userId: this._user(this.createdBy.cards[card._id]),
  210. dueAt: card.dueAt ? this._now(card.dueAt) : null,
  211. };
  212. // add labels
  213. if (card.labelIds) {
  214. cardToCreate.labelIds = card.labelIds.map((wekanId) => {
  215. return this.labels[wekanId];
  216. });
  217. }
  218. // add members {
  219. if(card.members) {
  220. const wekanMembers = [];
  221. // we can't just map, as some members may not have been mapped
  222. card.members.forEach((sourceMemberId) => {
  223. if(this.members[sourceMemberId]) {
  224. const wekanId = this.members[sourceMemberId];
  225. // we may map multiple Wekan members to the same wekan user
  226. // in which case we risk adding the same user multiple times
  227. if(!wekanMembers.find((wId) => wId === wekanId)){
  228. wekanMembers.push(wekanId);
  229. }
  230. }
  231. return true;
  232. });
  233. if(wekanMembers.length>0) {
  234. cardToCreate.members = wekanMembers;
  235. }
  236. }
  237. // insert card
  238. const cardId = Cards.direct.insert(cardToCreate);
  239. // keep track of Wekan id => WeKan id
  240. this.cards[card.id] = cardId;
  241. // log activity
  242. Activities.direct.insert({
  243. activityType: 'importCard',
  244. boardId,
  245. cardId,
  246. createdAt: this._now(),
  247. listId: cardToCreate.listId,
  248. source: {
  249. id: card._id,
  250. system: 'Wekan',
  251. },
  252. // we attribute the import to current user,
  253. // not the author of the original card
  254. userId: this._user(),
  255. });
  256. // add comments
  257. const comments = this.comments[card._id];
  258. if (comments) {
  259. comments.forEach((comment) => {
  260. const commentToCreate = {
  261. boardId,
  262. cardId,
  263. createdAt: this._now(comment.date),
  264. text: comment.text,
  265. // we attribute the comment to the original author, default to current user
  266. userId: this._user(comment.userId),
  267. };
  268. // dateLastActivity will be set from activity insert, no need to
  269. // update it ourselves
  270. const commentId = CardComments.direct.insert(commentToCreate);
  271. Activities.direct.insert({
  272. activityType: 'addComment',
  273. boardId: commentToCreate.boardId,
  274. cardId: commentToCreate.cardId,
  275. commentId,
  276. createdAt: this._now(commentToCreate.createdAt),
  277. // we attribute the addComment (not the import)
  278. // to the original author - it is needed by some UI elements.
  279. userId: commentToCreate.userId,
  280. });
  281. });
  282. }
  283. const attachments = this.attachments[card._id];
  284. const wekanCoverId = card.coverId;
  285. if (attachments) {
  286. attachments.forEach((att) => {
  287. const file = new FS.File();
  288. // Simulating file.attachData on the client generates multiple errors
  289. // - HEAD returns null, which causes exception down the line
  290. // - the template then tries to display the url to the attachment which causes other errors
  291. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  292. if(Meteor.isServer) {
  293. file.attachData(att.url, function (error) {
  294. file.boardId = boardId;
  295. file.cardId = cardId;
  296. if (error) {
  297. throw(error);
  298. } else {
  299. const wekanAtt = Attachments.insert(file, () => {
  300. // we do nothing
  301. });
  302. //
  303. if(wekanCoverId === att._id) {
  304. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  305. }
  306. }
  307. });
  308. }
  309. // todo XXX set cover - if need be
  310. });
  311. }
  312. result.push(cardId);
  313. });
  314. return result;
  315. }
  316. // Create labels if they do not exist and load this.labels.
  317. createLabels(wekanLabels, board) {
  318. wekanLabels.forEach((label) => {
  319. const color = label.color;
  320. const name = label.name;
  321. const existingLabel = board.getLabel(name, color);
  322. if (existingLabel) {
  323. this.labels[label.id] = existingLabel._id;
  324. } else {
  325. const idLabelCreated = board.pushLabel(name, color);
  326. this.labels[label.id] = idLabelCreated;
  327. }
  328. });
  329. }
  330. createLists(wekanLists, boardId) {
  331. wekanLists.forEach((list) => {
  332. const listToCreate = {
  333. archived: list.archived,
  334. boardId,
  335. // We are being defensing here by providing a default date (now) if the
  336. // creation date wasn't found on the action log. This happen on old
  337. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  338. // we require.
  339. createdAt: this._now(this.createdAt.lists[list.id]),
  340. title: list.title,
  341. };
  342. const listId = Lists.direct.insert(listToCreate);
  343. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  344. this.lists[list._id] = listId;
  345. // log activity
  346. Activities.direct.insert({
  347. activityType: 'importList',
  348. boardId,
  349. createdAt: this._now(),
  350. listId,
  351. source: {
  352. id: list._id,
  353. system: 'Wekan',
  354. },
  355. // We attribute the import to current user,
  356. // not the creator of the original object
  357. userId: this._user(),
  358. });
  359. });
  360. }
  361. // createChecklists(wekanChecklists) {
  362. // wekanChecklists.forEach((checklist) => {
  363. // // Create the checklist
  364. // const checklistToCreate = {
  365. // cardId: this.cards[checklist.cardId],
  366. // title: checklist.title,
  367. // createdAt: this._now(),
  368. // };
  369. // const checklistId = Checklists.direct.insert(checklistToCreate);
  370. // // Now add the items to the checklist
  371. // const itemsToCreate = [];
  372. // checklist.checkItems.forEach((item) => {
  373. // itemsToCreate.push({
  374. // _id: checklistId + itemsToCreate.length,
  375. // title: item.title,
  376. // isFinished: item.isFinished,
  377. // });
  378. // });
  379. // Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  380. // });
  381. // }
  382. parseActivities(wekanBoard) {
  383. wekanBoard.activities.forEach((activity) => {
  384. switch (activity.activityType) {
  385. case 'addAttachment': {
  386. // We have to be cautious, because the attachment could have been removed later.
  387. // In that case Wekan still reports its addition, but removes its 'url' field.
  388. // So we test for that
  389. const wekanAttachment = wekanBoard.attachments.filter((attachment) => {
  390. return attachment._id === activity.attachmentId;
  391. })[0];
  392. if(wekanAttachment.url) {
  393. // we cannot actually create the Wekan attachment, because we don't yet
  394. // have the cards to attach it to, so we store it in the instance variable.
  395. const wekanCardId = activity.cardId;
  396. if(!this.attachments[wekanCardId]) {
  397. this.attachments[wekanCardId] = [];
  398. }
  399. this.attachments[wekanCardId].push(wekanAttachment);
  400. }
  401. break;
  402. }
  403. case 'addComment': {
  404. const wekanComment = wekanBoard.comments.filter((comment) => {
  405. return comment._id === activity.commentId;
  406. })[0];
  407. const id = activity.cardId;
  408. if (!this.comments[id]) {
  409. this.comments[id] = [];
  410. }
  411. this.comments[id].push(wekanComment);
  412. break;
  413. }
  414. case 'createBoard': {
  415. this.createdAt.board = activity.createdAt;
  416. break;
  417. }
  418. case 'createCard': {
  419. const cardId = activity.cardId;
  420. this.createdAt.cards[cardId] = activity.createdAt;
  421. this.createdBy.cards[cardId] = activity.userId;
  422. break;
  423. }
  424. case 'createList': {
  425. const listId = activity.listId;
  426. this.createdAt.lists[listId] = activity.createdAt;
  427. break;
  428. }}
  429. });
  430. }
  431. check(board) {
  432. try {
  433. // check(data, {
  434. // membersMapping: Match.Optional(Object),
  435. // });
  436. this.checkActivities(board.activities);
  437. this.checkBoard(board);
  438. this.checkLabels(board.labels);
  439. this.checkLists(board.lists);
  440. this.checkCards(board.cards);
  441. // Checklists are not exported yet
  442. // this.checkChecklists(board.checklists);
  443. } catch (e) {
  444. throw new Meteor.Error('error-json-schema');
  445. }
  446. }
  447. create(board) {
  448. this.parseActivities(board);
  449. const boardId = this.createBoardAndLabels(board);
  450. this.createLists(board.lists, boardId);
  451. this.createCards(board.cards, boardId);
  452. // Checklists are not exported yet
  453. // this.createChecklists(board.checklists);
  454. // XXX add members
  455. return boardId;
  456. }
  457. }