wekanCreator.js 16 KB

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