trelloCreator.js 21 KB

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