trelloCreator.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. const DateString = Match.Where(function (dateAsString) {
  2. check(dateAsString, String);
  3. return moment(dateAsString, moment.ISO_8601).isValid();
  4. });
  5. export class TrelloCreator {
  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 Trello id
  11. // (so we only parse actions once!)
  12. this.createdAt = {
  13. board: null,
  14. cards: {},
  15. lists: {},
  16. };
  17. // The object creator Trello Id, indexed by the object Trello 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 Trello ID => Wekan ID
  23. this.labels = {};
  24. // Map of lists Trello ID => Wekan ID
  25. this.lists = {};
  26. // Map of cards Trello ID => Wekan ID
  27. this.cards = {};
  28. // Map of attachments Wekan ID => Wekan ID
  29. this.attachmentIds = {};
  30. // Map of checklists Wekan ID => Wekan ID
  31. this.checklists = {};
  32. // The comments, indexed by Trello card id (to map when importing cards)
  33. this.comments = {};
  34. // the members, indexed by Trello member id => Wekan user ID
  35. this.members = data.membersMapping ? data.membersMapping : {};
  36. // maps a trelloCardId to an array of trelloAttachments
  37. this.attachments = {};
  38. }
  39. /**
  40. * If dateString is provided,
  41. * return the Date it represents.
  42. * If not, will return the date when it was first called.
  43. * This is useful for us, as we want all import operations to
  44. * have the exact same date for easier later retrieval.
  45. *
  46. * @param {String} dateString a properly formatted Date
  47. */
  48. _now(dateString) {
  49. if(dateString) {
  50. return new Date(dateString);
  51. }
  52. if(!this._nowDate) {
  53. this._nowDate = new Date();
  54. }
  55. return this._nowDate;
  56. }
  57. /**
  58. * if trelloUserId is provided and we have a mapping,
  59. * return it.
  60. * Otherwise return current logged user.
  61. * @param trelloUserId
  62. * @private
  63. */
  64. _user(trelloUserId) {
  65. if(trelloUserId && this.members[trelloUserId]) {
  66. return this.members[trelloUserId];
  67. }
  68. return Meteor.userId();
  69. }
  70. checkActions(trelloActions) {
  71. check(trelloActions, [Match.ObjectIncluding({
  72. data: Object,
  73. date: DateString,
  74. type: String,
  75. })]);
  76. // XXX we could perform more thorough checks based on action type
  77. }
  78. checkBoard(trelloBoard) {
  79. check(trelloBoard, Match.ObjectIncluding({
  80. closed: Boolean,
  81. name: String,
  82. prefs: Match.ObjectIncluding({
  83. // XXX refine control by validating 'background' against a list of
  84. // allowed values (is it worth the maintenance?)
  85. background: String,
  86. permissionLevel: Match.Where((value) => {
  87. return ['org', 'private', 'public'].indexOf(value)>= 0;
  88. }),
  89. }),
  90. }));
  91. }
  92. checkCards(trelloCards) {
  93. check(trelloCards, [Match.ObjectIncluding({
  94. closed: Boolean,
  95. dateLastActivity: DateString,
  96. desc: String,
  97. idLabels: [String],
  98. idMembers: [String],
  99. name: String,
  100. pos: Number,
  101. })]);
  102. }
  103. checkLabels(trelloLabels) {
  104. check(trelloLabels, [Match.ObjectIncluding({
  105. // XXX refine control by validating 'color' against a list of allowed
  106. // values (is it worth the maintenance?)
  107. name: String,
  108. })]);
  109. }
  110. checkLists(trelloLists) {
  111. check(trelloLists, [Match.ObjectIncluding({
  112. closed: Boolean,
  113. name: String,
  114. })]);
  115. }
  116. checkChecklists(trelloChecklists) {
  117. check(trelloChecklists, [Match.ObjectIncluding({
  118. idBoard: String,
  119. idCard: String,
  120. name: String,
  121. checkItems: [Match.ObjectIncluding({
  122. state: String,
  123. name: String,
  124. })],
  125. })]);
  126. }
  127. // You must call parseActions before calling this one.
  128. createBoardAndLabels(trelloBoard) {
  129. const boardToCreate = {
  130. archived: trelloBoard.closed,
  131. color: this.getColor(trelloBoard.prefs.background),
  132. // very old boards won't have a creation activity so no creation date
  133. createdAt: this._now(this.createdAt.board),
  134. labels: [],
  135. members: [{
  136. userId: Meteor.userId(),
  137. isAdmin: true,
  138. isActive: true,
  139. isCommentOnly: false,
  140. }],
  141. permission: this.getPermission(trelloBoard.prefs.permissionLevel),
  142. slug: getSlug(trelloBoard.name) || 'board',
  143. stars: 0,
  144. title: trelloBoard.name,
  145. };
  146. // now add other members
  147. if(trelloBoard.memberships) {
  148. trelloBoard.memberships.forEach((trelloMembership) => {
  149. const trelloId = trelloMembership.idMember;
  150. // do we have a mapping?
  151. if(this.members[trelloId]) {
  152. const wekanId = this.members[trelloId];
  153. // do we already have it in our list?
  154. const wekanMember = boardToCreate.members.find((wekanMember) => wekanMember.userId === wekanId);
  155. if(wekanMember) {
  156. // we're already mapped, but maybe with lower rights
  157. if(!wekanMember.isAdmin) {
  158. wekanMember.isAdmin = this.getAdmin(trelloMembership.memberType);
  159. }
  160. } else {
  161. boardToCreate.members.push({
  162. userId: wekanId,
  163. isAdmin: this.getAdmin(trelloMembership.memberType),
  164. isActive: true,
  165. isCommentOnly: false,
  166. });
  167. }
  168. }
  169. });
  170. }
  171. trelloBoard.labels.forEach((label) => {
  172. const labelToCreate = {
  173. _id: Random.id(6),
  174. color: label.color ? label.color : 'black',
  175. name: label.name,
  176. };
  177. // We need to remember them by Trello ID, as this is the only ref we have
  178. // when importing cards.
  179. this.labels[label.id] = labelToCreate._id;
  180. boardToCreate.labels.push(labelToCreate);
  181. });
  182. const boardId = Boards.direct.insert(boardToCreate);
  183. Boards.direct.update(boardId, {$set: {modifiedAt: this._now()}});
  184. // log activity
  185. Activities.direct.insert({
  186. activityType: 'importBoard',
  187. boardId,
  188. createdAt: this._now(),
  189. source: {
  190. id: trelloBoard.id,
  191. system: 'Trello',
  192. url: trelloBoard.url,
  193. },
  194. // We attribute the import to current user,
  195. // not the author from the original object.
  196. userId: this._user(),
  197. });
  198. return boardId;
  199. }
  200. /**
  201. * Create the Wekan cards corresponding to the supplied Trello cards,
  202. * as well as all linked data: activities, comments, and attachments
  203. * @param trelloCards
  204. * @param boardId
  205. * @returns {Array}
  206. */
  207. createCards(trelloCards, boardId) {
  208. const result = [];
  209. trelloCards.forEach((card) => {
  210. const cardToCreate = {
  211. archived: card.closed,
  212. boardId,
  213. // very old boards won't have a creation activity so no creation date
  214. createdAt: this._now(this.createdAt.cards[card.id]),
  215. dateLastActivity: this._now(),
  216. description: card.desc,
  217. listId: this.lists[card.idList],
  218. sort: card.pos,
  219. title: card.name,
  220. // we attribute the card to its creator if available
  221. userId: this._user(this.createdBy.cards[card.id]),
  222. dueAt: card.due ? this._now(card.due) : null,
  223. };
  224. // add labels
  225. if (card.idLabels) {
  226. cardToCreate.labelIds = card.idLabels.map((trelloId) => {
  227. return this.labels[trelloId];
  228. });
  229. }
  230. // add members {
  231. if(card.idMembers) {
  232. const wekanMembers = [];
  233. // we can't just map, as some members may not have been mapped
  234. card.idMembers.forEach((trelloId) => {
  235. if(this.members[trelloId]) {
  236. const wekanId = this.members[trelloId];
  237. // we may map multiple Trello members to the same wekan user
  238. // in which case we risk adding the same user multiple times
  239. if(!wekanMembers.find((wId) => wId === wekanId)){
  240. wekanMembers.push(wekanId);
  241. }
  242. }
  243. return true;
  244. });
  245. if(wekanMembers.length>0) {
  246. cardToCreate.members = wekanMembers;
  247. }
  248. }
  249. // insert card
  250. const cardId = Cards.direct.insert(cardToCreate);
  251. // keep track of Trello id => WeKan id
  252. this.cards[card.id] = cardId;
  253. // log activity
  254. // Activities.direct.insert({
  255. // activityType: 'importCard',
  256. // boardId,
  257. // cardId,
  258. // createdAt: this._now(),
  259. // listId: cardToCreate.listId,
  260. // source: {
  261. // id: card.id,
  262. // system: 'Trello',
  263. // url: card.url,
  264. // },
  265. // // we attribute the import to current user,
  266. // // not the author of the original card
  267. // userId: this._user(),
  268. // });
  269. // add comments
  270. const comments = this.comments[card.id];
  271. if (comments) {
  272. comments.forEach((comment) => {
  273. const commentToCreate = {
  274. boardId,
  275. cardId,
  276. createdAt: this._now(comment.date),
  277. text: comment.data.text,
  278. // we attribute the comment to the original author, default to current user
  279. userId: this._user(comment.idMemberCreator),
  280. };
  281. // dateLastActivity will be set from activity insert, no need to
  282. // update it ourselves
  283. const commentId = CardComments.direct.insert(commentToCreate);
  284. // We need to keep adding comment activities this way with Trello
  285. // because it doesn't provide a comment ID
  286. Activities.direct.insert({
  287. activityType: 'addComment',
  288. boardId: commentToCreate.boardId,
  289. cardId: commentToCreate.cardId,
  290. commentId,
  291. createdAt: this._now(comment.date),
  292. // we attribute the addComment (not the import)
  293. // to the original author - it is needed by some UI elements.
  294. userId: commentToCreate.userId,
  295. });
  296. });
  297. }
  298. const attachments = this.attachments[card.id];
  299. const trelloCoverId = card.idAttachmentCover;
  300. if (attachments) {
  301. attachments.forEach((att) => {
  302. const file = new FS.File();
  303. // Simulating file.attachData on the client generates multiple errors
  304. // - HEAD returns null, which causes exception down the line
  305. // - the template then tries to display the url to the attachment which causes other errors
  306. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  307. const self = this;
  308. if(Meteor.isServer) {
  309. file.attachData(att.url, function (error) {
  310. file.boardId = boardId;
  311. file.cardId = cardId;
  312. file.userId = self._user(att.idMemberCreator);
  313. // The field source will only be used to prevent adding
  314. // attachments' related activities automatically
  315. file.source = 'import';
  316. if (error) {
  317. throw(error);
  318. } else {
  319. const wekanAtt = Attachments.insert(file, () => {
  320. // we do nothing
  321. });
  322. self.attachmentIds[att.id] = wekanAtt._id;
  323. //
  324. if(trelloCoverId === att.id) {
  325. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  326. }
  327. }
  328. });
  329. }
  330. // todo XXX set cover - if need be
  331. });
  332. }
  333. result.push(cardId);
  334. });
  335. return result;
  336. }
  337. // Create labels if they do not exist and load this.labels.
  338. createLabels(trelloLabels, board) {
  339. trelloLabels.forEach((label) => {
  340. const color = label.color;
  341. const name = label.name;
  342. const existingLabel = board.getLabel(name, color);
  343. if (existingLabel) {
  344. this.labels[label.id] = existingLabel._id;
  345. } else {
  346. const idLabelCreated = board.pushLabel(name, color);
  347. this.labels[label.id] = idLabelCreated;
  348. }
  349. });
  350. }
  351. createLists(trelloLists, boardId) {
  352. trelloLists.forEach((list) => {
  353. const listToCreate = {
  354. archived: list.closed,
  355. boardId,
  356. // We are being defensing here by providing a default date (now) if the
  357. // creation date wasn't found on the action log. This happen on old
  358. // Trello boards (eg from 2013) that didn't log the 'createList' action
  359. // we require.
  360. createdAt: this._now(this.createdAt.lists[list.id]),
  361. title: list.name,
  362. };
  363. const listId = Lists.direct.insert(listToCreate);
  364. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  365. this.lists[list.id] = listId;
  366. // log activity
  367. // Activities.direct.insert({
  368. // activityType: 'importList',
  369. // boardId,
  370. // createdAt: this._now(),
  371. // listId,
  372. // source: {
  373. // id: list.id,
  374. // system: 'Trello',
  375. // },
  376. // // We attribute the import to current user,
  377. // // not the creator of the original object
  378. // userId: this._user(),
  379. // });
  380. });
  381. }
  382. createChecklists(trelloChecklists) {
  383. trelloChecklists.forEach((checklist) => {
  384. if (this.cards[checklist.idCard]) {
  385. // Create the checklist
  386. const checklistToCreate = {
  387. cardId: this.cards[checklist.idCard],
  388. title: checklist.name,
  389. createdAt: this._now(),
  390. sort: checklist.pos,
  391. };
  392. const checklistId = Checklists.direct.insert(checklistToCreate);
  393. // keep track of Trello id => WeKan id
  394. this.checklists[checklist.id] = checklistId;
  395. // Now add the items to the checklist
  396. const itemsToCreate = [];
  397. checklist.checkItems.forEach((item) => {
  398. itemsToCreate.push({
  399. _id: checklistId + itemsToCreate.length,
  400. title: item.name,
  401. isFinished: item.state === 'complete',
  402. sort: item.pos,
  403. });
  404. });
  405. Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  406. }
  407. });
  408. }
  409. getAdmin(trelloMemberType) {
  410. return trelloMemberType === 'admin';
  411. }
  412. getColor(trelloColorCode) {
  413. // trello color name => wekan color
  414. const mapColors = {
  415. 'blue': 'belize',
  416. 'orange': 'pumpkin',
  417. 'green': 'nephritis',
  418. 'red': 'pomegranate',
  419. 'purple': 'wisteria',
  420. 'pink': 'pomegranate',
  421. 'lime': 'nephritis',
  422. 'sky': 'belize',
  423. 'grey': 'midnight',
  424. };
  425. const wekanColor = mapColors[trelloColorCode];
  426. return wekanColor || Boards.simpleSchema()._schema.color.allowedValues[0];
  427. }
  428. getPermission(trelloPermissionCode) {
  429. if (trelloPermissionCode === 'public') {
  430. return 'public';
  431. }
  432. // Wekan does NOT have organization level, so we default both 'private' and
  433. // 'org' to private.
  434. return 'private';
  435. }
  436. parseActions(trelloActions) {
  437. trelloActions.forEach((action) => {
  438. if (action.type === 'addAttachmentToCard') {
  439. // We have to be cautious, because the attachment could have been removed later.
  440. // In that case Trello still reports its addition, but removes its 'url' field.
  441. // So we test for that
  442. const trelloAttachment = action.data.attachment;
  443. // We need the idMemberCreator
  444. trelloAttachment.idMemberCreator = action.idMemberCreator;
  445. if(trelloAttachment.url) {
  446. // we cannot actually create the Wekan attachment, because we don't yet
  447. // have the cards to attach it to, so we store it in the instance variable.
  448. const trelloCardId = action.data.card.id;
  449. if(!this.attachments[trelloCardId]) {
  450. this.attachments[trelloCardId] = [];
  451. }
  452. this.attachments[trelloCardId].push(trelloAttachment);
  453. }
  454. } else if (action.type === 'commentCard') {
  455. const id = action.data.card.id;
  456. if (this.comments[id]) {
  457. this.comments[id].push(action);
  458. } else {
  459. this.comments[id] = [action];
  460. }
  461. } else if (action.type === 'createBoard') {
  462. this.createdAt.board = action.date;
  463. } else if (action.type === 'createCard') {
  464. const cardId = action.data.card.id;
  465. this.createdAt.cards[cardId] = action.date;
  466. this.createdBy.cards[cardId] = action.idMemberCreator;
  467. } else if (action.type === 'createList') {
  468. const listId = action.data.list.id;
  469. this.createdAt.lists[listId] = action.date;
  470. }
  471. });
  472. }
  473. importActions(actions, boardId) {
  474. actions.forEach((action) => {
  475. switch (action.type) {
  476. // Board related actions
  477. // TODO: addBoardMember, removeBoardMember
  478. case 'createBoard': {
  479. Activities.direct.insert({
  480. userId: this._user(action.idMemberCreator),
  481. type: 'board',
  482. activityTypeId: boardId,
  483. activityType: 'createBoard',
  484. boardId,
  485. createdAt: this._now(action.date),
  486. });
  487. break;
  488. }
  489. // List related activities
  490. // TODO: removeList, archivedList
  491. case 'createList': {
  492. Activities.direct.insert({
  493. userId: this._user(action.idMemberCreator),
  494. type: 'list',
  495. activityType: 'createList',
  496. listId: this.lists[action.data.list.id],
  497. boardId,
  498. createdAt: this._now(action.date),
  499. });
  500. break;
  501. }
  502. // Card related activities
  503. // TODO: archivedCard, restoredCard, joinMember, unjoinMember
  504. case 'createCard': {
  505. Activities.direct.insert({
  506. userId: this._user(action.idMemberCreator),
  507. activityType: 'createCard',
  508. listId: this.lists[action.data.list.id],
  509. cardId: this.cards[action.data.card.id],
  510. boardId,
  511. createdAt: this._now(action.date),
  512. });
  513. break;
  514. }
  515. case 'updateCard': {
  516. if (action.data.old.idList) {
  517. Activities.direct.insert({
  518. userId: this._user(action.idMemberCreator),
  519. oldListId: this.lists[action.data.old.idList],
  520. activityType: 'moveCard',
  521. listId: this.lists[action.data.listAfter.id],
  522. cardId: this.cards[action.data.card.id],
  523. boardId,
  524. createdAt: this._now(action.date),
  525. });
  526. }
  527. break;
  528. }
  529. // Comment related activities
  530. // Trello doesn't export the comment id
  531. // Attachment related activities
  532. case 'addAttachmentToCard': {
  533. Activities.direct.insert({
  534. userId: this._user(action.idMemberCreator),
  535. type: 'card',
  536. activityType: 'addAttachment',
  537. attachmentId: this.attachmentIds[action.data.attachment.id],
  538. cardId: this.cards[action.data.card.id],
  539. boardId,
  540. createdAt: this._now(action.date),
  541. });
  542. break;
  543. }
  544. // Checklist related activities
  545. case 'addChecklistToCard': {
  546. Activities.direct.insert({
  547. userId: this._user(action.idMemberCreator),
  548. activityType: 'addChecklist',
  549. cardId: this.cards[action.data.card.id],
  550. checklistId: this.checklists[action.data.checklist.id],
  551. boardId,
  552. createdAt: this._now(action.date),
  553. });
  554. break;
  555. }}
  556. // Trello doesn't have an add checklist item action
  557. });
  558. }
  559. check(board) {
  560. try {
  561. // check(data, {
  562. // membersMapping: Match.Optional(Object),
  563. // });
  564. this.checkActions(board.actions);
  565. this.checkBoard(board);
  566. this.checkLabels(board.labels);
  567. this.checkLists(board.lists);
  568. this.checkCards(board.cards);
  569. this.checkChecklists(board.checklists);
  570. } catch (e) {
  571. throw new Meteor.Error('error-json-schema');
  572. }
  573. }
  574. create(board, currentBoardId) {
  575. // TODO : Make isSandstorm variable global
  576. const isSandstorm = Meteor.settings && Meteor.settings.public &&
  577. Meteor.settings.public.sandstorm;
  578. if (isSandstorm && currentBoardId) {
  579. const currentBoard = Boards.findOne(currentBoardId);
  580. currentBoard.archive();
  581. }
  582. this.parseActions(board.actions);
  583. const boardId = this.createBoardAndLabels(board);
  584. this.createLists(board.lists, boardId);
  585. this.createCards(board.cards, boardId);
  586. this.createChecklists(board.checklists);
  587. this.importActions(board.actions, boardId);
  588. // XXX add members
  589. return boardId;
  590. }
  591. }