trelloCreator.js 22 KB

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