trelloCreator.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. // FIXME: Change to new model
  359. file.attachData(att.url, function(error) {
  360. file.boardId = boardId;
  361. file.cardId = cardId;
  362. file.userId = self._user(att.idMemberCreator);
  363. // The field source will only be used to prevent adding
  364. // attachments' related activities automatically
  365. file.source = 'import';
  366. if (error) {
  367. throw error;
  368. } else {
  369. const wekanAtt = Attachments.insert(file, () => {
  370. // we do nothing
  371. });
  372. self.attachmentIds[att.id] = wekanAtt._id;
  373. //
  374. if (trelloCoverId === att.id) {
  375. Cards.direct.update(cardId, {
  376. $set: { coverId: wekanAtt._id },
  377. });
  378. }
  379. }
  380. });
  381. }
  382. // todo XXX set cover - if need be
  383. });
  384. }
  385. result.push(cardId);
  386. });
  387. return result;
  388. }
  389. // Create labels if they do not exist and load this.labels.
  390. createLabels(trelloLabels, board) {
  391. trelloLabels.forEach(label => {
  392. const color = label.color;
  393. const name = label.name;
  394. const existingLabel = board.getLabel(name, color);
  395. if (existingLabel) {
  396. this.labels[label.id] = existingLabel._id;
  397. } else {
  398. const idLabelCreated = board.pushLabel(name, color);
  399. this.labels[label.id] = idLabelCreated;
  400. }
  401. });
  402. }
  403. createLists(trelloLists, boardId) {
  404. trelloLists.forEach(list => {
  405. const listToCreate = {
  406. archived: list.closed,
  407. boardId,
  408. // We are being defensing here by providing a default date (now) if the
  409. // creation date wasn't found on the action log. This happen on old
  410. // Trello boards (eg from 2013) that didn't log the 'createList' action
  411. // we require.
  412. createdAt: this._now(this.createdAt.lists[list.id]),
  413. title: list.name,
  414. sort: list.pos,
  415. };
  416. const listId = Lists.direct.insert(listToCreate);
  417. Lists.direct.update(listId, { $set: { updatedAt: this._now() } });
  418. this.lists[list.id] = listId;
  419. // log activity
  420. // Activities.direct.insert({
  421. // activityType: 'importList',
  422. // boardId,
  423. // createdAt: this._now(),
  424. // listId,
  425. // source: {
  426. // id: list.id,
  427. // system: 'Trello',
  428. // },
  429. // // We attribute the import to current user,
  430. // // not the creator of the original object
  431. // userId: this._user(),
  432. // });
  433. });
  434. }
  435. createSwimlanes(boardId) {
  436. const swimlaneToCreate = {
  437. archived: false,
  438. boardId,
  439. // We are being defensing here by providing a default date (now) if the
  440. // creation date wasn't found on the action log. This happen on old
  441. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  442. // we require.
  443. createdAt: this._now(),
  444. title: 'Default',
  445. sort: 1,
  446. };
  447. const swimlaneId = Swimlanes.direct.insert(swimlaneToCreate);
  448. Swimlanes.direct.update(swimlaneId, { $set: { updatedAt: this._now() } });
  449. this.swimlane = swimlaneId;
  450. }
  451. createChecklists(trelloChecklists) {
  452. trelloChecklists.forEach(checklist => {
  453. if (this.cards[checklist.idCard]) {
  454. // Create the checklist
  455. const checklistToCreate = {
  456. cardId: this.cards[checklist.idCard],
  457. title: checklist.name,
  458. createdAt: this._now(),
  459. sort: checklist.pos,
  460. };
  461. const checklistId = Checklists.direct.insert(checklistToCreate);
  462. // keep track of Trello id => Wekan id
  463. this.checklists[checklist.id] = checklistId;
  464. // Now add the items to the checklistItems
  465. let counter = 0;
  466. checklist.checkItems.forEach(item => {
  467. counter++;
  468. const checklistItemTocreate = {
  469. _id: checklistId + counter,
  470. title: item.name,
  471. checklistId: this.checklists[checklist.id],
  472. cardId: this.cards[checklist.idCard],
  473. sort: item.pos,
  474. isFinished: item.state === 'complete',
  475. };
  476. ChecklistItems.direct.insert(checklistItemTocreate);
  477. });
  478. }
  479. });
  480. }
  481. getAdmin(trelloMemberType) {
  482. return trelloMemberType === 'admin';
  483. }
  484. getColor(trelloColorCode) {
  485. // trello color name => wekan color
  486. const mapColors = {
  487. blue: 'belize',
  488. orange: 'pumpkin',
  489. green: 'nephritis',
  490. red: 'pomegranate',
  491. purple: 'wisteria',
  492. pink: 'moderatepink',
  493. lime: 'limegreen',
  494. sky: 'strongcyan',
  495. grey: 'midnight',
  496. };
  497. const wekanColor = mapColors[trelloColorCode];
  498. return wekanColor || Boards.simpleSchema()._schema.color.allowedValues[0];
  499. }
  500. getPermission(trelloPermissionCode) {
  501. if (trelloPermissionCode === 'public') {
  502. return 'public';
  503. }
  504. // Wekan does NOT have organization level, so we default both 'private' and
  505. // 'org' to private.
  506. return 'private';
  507. }
  508. parseActions(trelloActions) {
  509. trelloActions.forEach(action => {
  510. if (action.type === 'addAttachmentToCard') {
  511. // We have to be cautious, because the attachment could have been removed later.
  512. // In that case Trello still reports its addition, but removes its 'url' field.
  513. // So we test for that
  514. const trelloAttachment = action.data.attachment;
  515. // We need the idMemberCreator
  516. trelloAttachment.idMemberCreator = action.idMemberCreator;
  517. if (trelloAttachment.url) {
  518. // we cannot actually create the Wekan attachment, because we don't yet
  519. // have the cards to attach it to, so we store it in the instance variable.
  520. const trelloCardId = action.data.card.id;
  521. if (!this.attachments[trelloCardId]) {
  522. this.attachments[trelloCardId] = [];
  523. }
  524. this.attachments[trelloCardId].push(trelloAttachment);
  525. }
  526. } else if (action.type === 'commentCard') {
  527. const id = action.data.card.id;
  528. if (this.comments[id]) {
  529. this.comments[id].push(action);
  530. } else {
  531. this.comments[id] = [action];
  532. }
  533. } else if (action.type === 'createBoard') {
  534. this.createdAt.board = action.date;
  535. } else if (action.type === 'createCard') {
  536. const cardId = action.data.card.id;
  537. this.createdAt.cards[cardId] = action.date;
  538. this.createdBy.cards[cardId] = action.idMemberCreator;
  539. } else if (action.type === 'createList') {
  540. const listId = action.data.list.id;
  541. this.createdAt.lists[listId] = action.date;
  542. }
  543. });
  544. }
  545. importActions(actions, boardId) {
  546. actions.forEach(action => {
  547. switch (action.type) {
  548. // Board related actions
  549. // TODO: addBoardMember, removeBoardMember
  550. case 'createBoard': {
  551. Activities.direct.insert({
  552. userId: this._user(action.idMemberCreator),
  553. type: 'board',
  554. activityTypeId: boardId,
  555. activityType: 'createBoard',
  556. boardId,
  557. createdAt: this._now(action.date),
  558. });
  559. break;
  560. }
  561. // List related activities
  562. // TODO: removeList, archivedList
  563. case 'createList': {
  564. Activities.direct.insert({
  565. userId: this._user(action.idMemberCreator),
  566. type: 'list',
  567. activityType: 'createList',
  568. listId: this.lists[action.data.list.id],
  569. boardId,
  570. createdAt: this._now(action.date),
  571. });
  572. break;
  573. }
  574. // Card related activities
  575. // TODO: archivedCard, restoredCard, joinMember, unjoinMember
  576. case 'createCard': {
  577. Activities.direct.insert({
  578. userId: this._user(action.idMemberCreator),
  579. activityType: 'createCard',
  580. listId: this.lists[action.data.list.id],
  581. cardId: this.cards[action.data.card.id],
  582. boardId,
  583. createdAt: this._now(action.date),
  584. });
  585. break;
  586. }
  587. case 'updateCard': {
  588. if (action.data.old.idList) {
  589. Activities.direct.insert({
  590. userId: this._user(action.idMemberCreator),
  591. oldListId: this.lists[action.data.old.idList],
  592. activityType: 'moveCard',
  593. listId: this.lists[action.data.listAfter.id],
  594. cardId: this.cards[action.data.card.id],
  595. boardId,
  596. createdAt: this._now(action.date),
  597. });
  598. }
  599. break;
  600. }
  601. // Comment related activities
  602. // Trello doesn't export the comment id
  603. // Attachment related activities
  604. case 'addAttachmentToCard': {
  605. Activities.direct.insert({
  606. userId: this._user(action.idMemberCreator),
  607. type: 'card',
  608. activityType: 'addAttachment',
  609. attachmentId: this.attachmentIds[action.data.attachment.id],
  610. cardId: this.cards[action.data.card.id],
  611. boardId,
  612. createdAt: this._now(action.date),
  613. });
  614. break;
  615. }
  616. // Checklist related activities
  617. case 'addChecklistToCard': {
  618. Activities.direct.insert({
  619. userId: this._user(action.idMemberCreator),
  620. activityType: 'addChecklist',
  621. cardId: this.cards[action.data.card.id],
  622. checklistId: this.checklists[action.data.checklist.id],
  623. boardId,
  624. createdAt: this._now(action.date),
  625. });
  626. break;
  627. }
  628. }
  629. // Trello doesn't have an add checklist item action
  630. });
  631. }
  632. check(board) {
  633. try {
  634. // check(data, {
  635. // membersMapping: Match.Optional(Object),
  636. // });
  637. this.checkActions(board.actions);
  638. this.checkBoard(board);
  639. this.checkLabels(board.labels);
  640. this.checkLists(board.lists);
  641. this.checkCards(board.cards);
  642. this.checkChecklists(board.checklists);
  643. } catch (e) {
  644. throw new Meteor.Error('error-json-schema');
  645. }
  646. }
  647. create(board, currentBoardId) {
  648. // TODO : Make isSandstorm variable global
  649. const isSandstorm =
  650. Meteor.settings &&
  651. Meteor.settings.public &&
  652. Meteor.settings.public.sandstorm;
  653. if (isSandstorm && currentBoardId) {
  654. const currentBoard = Boards.findOne(currentBoardId);
  655. currentBoard.archive();
  656. }
  657. this.parseActions(board.actions);
  658. const boardId = this.createBoardAndLabels(board);
  659. this.createLists(board.lists, boardId);
  660. this.createSwimlanes(boardId);
  661. this.createCards(board.cards, boardId);
  662. this.createChecklists(board.checklists);
  663. this.importActions(board.actions, boardId);
  664. // XXX add members
  665. return boardId;
  666. }
  667. }