wekanCreator.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. activityType: String,
  69. createdAt: DateString,
  70. })]);
  71. // XXX we could perform more thorough checks based on action type
  72. }
  73. checkBoard(wekanBoard) {
  74. check(wekanBoard, Match.ObjectIncluding({
  75. archived: Boolean,
  76. title: String,
  77. // XXX refine control by validating 'color' against a list of
  78. // allowed values (is it worth the maintenance?)
  79. color: String,
  80. permission: Match.Where((value) => {
  81. return ['private', 'public'].indexOf(value)>= 0;
  82. }),
  83. }));
  84. }
  85. checkCards(wekanCards) {
  86. check(wekanCards, [Match.ObjectIncluding({
  87. archived: Boolean,
  88. dateLastActivity: DateString,
  89. labelIds: [String],
  90. title: String,
  91. sort: Number,
  92. })]);
  93. }
  94. checkLabels(wekanLabels) {
  95. check(wekanLabels, [Match.ObjectIncluding({
  96. // XXX refine control by validating 'color' against a list of allowed
  97. // values (is it worth the maintenance?)
  98. color: String,
  99. })]);
  100. }
  101. checkLists(wekanLists) {
  102. check(wekanLists, [Match.ObjectIncluding({
  103. archived: Boolean,
  104. title: String,
  105. })]);
  106. }
  107. checkChecklists(wekanChecklists) {
  108. check(wekanChecklists, [Match.ObjectIncluding({
  109. cardId: String,
  110. title: String,
  111. items: [Match.ObjectIncluding({
  112. isFinished: Boolean,
  113. title: String,
  114. })],
  115. })]);
  116. }
  117. // You must call parseActions before calling this one.
  118. createBoardAndLabels(wekanBoard) {
  119. const boardToCreate = {
  120. archived: wekanBoard.archived,
  121. color: wekanBoard.color,
  122. // very old boards won't have a creation activity so no creation date
  123. createdAt: this._now(wekanBoard.createdAt),
  124. labels: [],
  125. members: [{
  126. userId: Meteor.userId(),
  127. isAdmin: true,
  128. isActive: true,
  129. isCommentOnly: false,
  130. }],
  131. permission: wekanBoard.permission,
  132. slug: getSlug(wekanBoard.title) || 'board',
  133. stars: 0,
  134. title: wekanBoard.title,
  135. };
  136. // now add other members
  137. if(wekanBoard.members) {
  138. wekanBoard.members.forEach((wekanMember) => {
  139. const wekanId = wekanMember.userId;
  140. // do we have a mapping?
  141. if(this.members[wekanId]) {
  142. const wekanId = this.members[wekanId];
  143. // do we already have it in our list?
  144. const wekanMember = boardToCreate.members.find((wekanMember) => wekanMember.userId === wekanId);
  145. if(!wekanMember) {
  146. boardToCreate.members.push({
  147. userId: wekanId,
  148. isAdmin: wekanMember.isAdmin,
  149. isActive: true,
  150. isCommentOnly: false,
  151. });
  152. }
  153. }
  154. });
  155. }
  156. wekanBoard.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: wekanBoard.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.date),
  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. Activities.direct.insert({
  268. activityType: 'addComment',
  269. boardId: commentToCreate.boardId,
  270. cardId: commentToCreate.cardId,
  271. commentId,
  272. createdAt: this._now(commentToCreate.createdAt),
  273. // we attribute the addComment (not the import)
  274. // to the original author - it is needed by some UI elements.
  275. userId: commentToCreate.userId,
  276. });
  277. });
  278. }
  279. const attachments = this.attachments[card._id];
  280. const wekanCoverId = card.coverId;
  281. if (attachments) {
  282. attachments.forEach((att) => {
  283. const file = new FS.File();
  284. // Simulating file.attachData on the client generates multiple errors
  285. // - HEAD returns null, which causes exception down the line
  286. // - the template then tries to display the url to the attachment which causes other errors
  287. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  288. if(Meteor.isServer) {
  289. if (att.url) {
  290. file.attachData(att.url, function (error) {
  291. file.boardId = boardId;
  292. file.cardId = cardId;
  293. if (error) {
  294. throw(error);
  295. } else {
  296. const wekanAtt = Attachments.insert(file, () => {
  297. // we do nothing
  298. });
  299. //
  300. if(wekanCoverId === att._id) {
  301. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  302. }
  303. }
  304. });
  305. } else if (att.file) {
  306. file.attachData(new Buffer(att.file, 'base64'), {type: att.type}, (error) => {
  307. file.name(att.name);
  308. file.boardId = boardId;
  309. file.cardId = cardId;
  310. if (error) {
  311. throw(error);
  312. } else {
  313. const wekanAtt = Attachments.insert(file, () => {
  314. // we do nothing
  315. });
  316. //
  317. if(wekanCoverId === att._id) {
  318. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  319. }
  320. }
  321. });
  322. }
  323. }
  324. // todo XXX set cover - if need be
  325. });
  326. }
  327. result.push(cardId);
  328. });
  329. return result;
  330. }
  331. // Create labels if they do not exist and load this.labels.
  332. createLabels(wekanLabels, board) {
  333. wekanLabels.forEach((label) => {
  334. const color = label.color;
  335. const name = label.name;
  336. const existingLabel = board.getLabel(name, color);
  337. if (existingLabel) {
  338. this.labels[label.id] = existingLabel._id;
  339. } else {
  340. const idLabelCreated = board.pushLabel(name, color);
  341. this.labels[label.id] = idLabelCreated;
  342. }
  343. });
  344. }
  345. createLists(wekanLists, boardId) {
  346. wekanLists.forEach((list) => {
  347. const listToCreate = {
  348. archived: list.archived,
  349. boardId,
  350. // We are being defensing here by providing a default date (now) if the
  351. // creation date wasn't found on the action log. This happen on old
  352. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  353. // we require.
  354. createdAt: this._now(this.createdAt.lists[list.id]),
  355. title: list.title,
  356. };
  357. const listId = Lists.direct.insert(listToCreate);
  358. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  359. this.lists[list._id] = listId;
  360. // log activity
  361. Activities.direct.insert({
  362. activityType: 'importList',
  363. boardId,
  364. createdAt: this._now(),
  365. listId,
  366. source: {
  367. id: list._id,
  368. system: 'Wekan',
  369. },
  370. // We attribute the import to current user,
  371. // not the creator of the original object
  372. userId: this._user(),
  373. });
  374. });
  375. }
  376. createChecklists(wekanChecklists) {
  377. wekanChecklists.forEach((checklist) => {
  378. // Create the checklist
  379. const checklistToCreate = {
  380. cardId: this.cards[checklist.cardId],
  381. title: checklist.title,
  382. createdAt: checklist.createdAt,
  383. };
  384. const checklistId = Checklists.direct.insert(checklistToCreate);
  385. // Now add the items to the checklist
  386. const itemsToCreate = [];
  387. checklist.items.forEach((item) => {
  388. itemsToCreate.push({
  389. _id: checklistId + itemsToCreate.length,
  390. title: item.title,
  391. isFinished: item.isFinished,
  392. });
  393. });
  394. Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  395. });
  396. }
  397. parseActivities(wekanBoard) {
  398. wekanBoard.activities.forEach((activity) => {
  399. switch (activity.activityType) {
  400. case 'addAttachment': {
  401. // We have to be cautious, because the attachment could have been removed later.
  402. // In that case Wekan still reports its addition, but removes its 'url' field.
  403. // So we test for that
  404. const wekanAttachment = wekanBoard.attachments.filter((attachment) => {
  405. return attachment._id === activity.attachmentId;
  406. })[0];
  407. if(wekanAttachment.url || wekanAttachment.file) {
  408. // we cannot actually create the Wekan attachment, because we don't yet
  409. // have the cards to attach it to, so we store it in the instance variable.
  410. const wekanCardId = activity.cardId;
  411. if(!this.attachments[wekanCardId]) {
  412. this.attachments[wekanCardId] = [];
  413. }
  414. this.attachments[wekanCardId].push(wekanAttachment);
  415. }
  416. break;
  417. }
  418. case 'addComment': {
  419. const wekanComment = wekanBoard.comments.filter((comment) => {
  420. return comment._id === activity.commentId;
  421. })[0];
  422. const id = activity.cardId;
  423. if (!this.comments[id]) {
  424. this.comments[id] = [];
  425. }
  426. this.comments[id].push(wekanComment);
  427. break;
  428. }
  429. case 'createBoard': {
  430. this.createdAt.board = activity.createdAt;
  431. break;
  432. }
  433. case 'createCard': {
  434. const cardId = activity.cardId;
  435. this.createdAt.cards[cardId] = activity.createdAt;
  436. this.createdBy.cards[cardId] = activity.userId;
  437. break;
  438. }
  439. case 'createList': {
  440. const listId = activity.listId;
  441. this.createdAt.lists[listId] = activity.createdAt;
  442. break;
  443. }}
  444. });
  445. }
  446. check(board) {
  447. try {
  448. // check(data, {
  449. // membersMapping: Match.Optional(Object),
  450. // });
  451. this.checkActivities(board.activities);
  452. this.checkBoard(board);
  453. this.checkLabels(board.labels);
  454. this.checkLists(board.lists);
  455. this.checkCards(board.cards);
  456. this.checkChecklists(board.checklists);
  457. } catch (e) {
  458. throw new Meteor.Error('error-json-schema');
  459. }
  460. }
  461. create(board, currentBoardId) {
  462. // TODO : Make isSandstorm variable global
  463. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  464. Meteor.settings.public.sandstorm;
  465. if (isSandstorm && currentBoardId) {
  466. const currentBoard = Boards.findOne(currentBoardId);
  467. currentBoard.archive();
  468. }
  469. this.parseActivities(board);
  470. const boardId = this.createBoardAndLabels(board);
  471. this.createLists(board.lists, boardId);
  472. this.createCards(board.cards, boardId);
  473. this.createChecklists(board.checklists);
  474. // XXX add members
  475. return boardId;
  476. }
  477. }