wekanCreator.js 16 KB

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