trelloCreator.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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. // insert card
  276. const cardId = Cards.direct.insert(cardToCreate);
  277. // keep track of Trello id => Wekan id
  278. this.cards[card.id] = cardId;
  279. // log activity
  280. // Activities.direct.insert({
  281. // activityType: 'importCard',
  282. // boardId,
  283. // cardId,
  284. // createdAt: this._now(),
  285. // listId: cardToCreate.listId,
  286. // source: {
  287. // id: card.id,
  288. // system: 'Trello',
  289. // url: card.url,
  290. // },
  291. // // we attribute the import to current user,
  292. // // not the author of the original card
  293. // userId: this._user(),
  294. // });
  295. // add comments
  296. const comments = this.comments[card.id];
  297. if (comments) {
  298. comments.forEach(comment => {
  299. const commentToCreate = {
  300. boardId,
  301. cardId,
  302. createdAt: this._now(comment.date),
  303. text: comment.data.text,
  304. // we attribute the comment to the original author, default to current user
  305. userId: this._user(comment.idMemberCreator),
  306. };
  307. // dateLastActivity will be set from activity insert, no need to
  308. // update it ourselves
  309. const commentId = CardComments.direct.insert(commentToCreate);
  310. // We need to keep adding comment activities this way with Trello
  311. // because it doesn't provide a comment ID
  312. Activities.direct.insert({
  313. activityType: 'addComment',
  314. boardId: commentToCreate.boardId,
  315. cardId: commentToCreate.cardId,
  316. commentId,
  317. createdAt: this._now(comment.date),
  318. // we attribute the addComment (not the import)
  319. // to the original author - it is needed by some UI elements.
  320. userId: commentToCreate.userId,
  321. });
  322. });
  323. }
  324. const attachments = this.attachments[card.id];
  325. const trelloCoverId = card.idAttachmentCover;
  326. if (attachments) {
  327. attachments.forEach(att => {
  328. const file = new FS.File();
  329. // Simulating file.attachData on the client generates multiple errors
  330. // - HEAD returns null, which causes exception down the line
  331. // - the template then tries to display the url to the attachment which causes other errors
  332. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  333. const self = this;
  334. if (Meteor.isServer) {
  335. // FIXME: Change to new model
  336. file.attachData(att.url, function(error) {
  337. file.boardId = boardId;
  338. file.cardId = cardId;
  339. file.userId = self._user(att.idMemberCreator);
  340. // The field source will only be used to prevent adding
  341. // attachments' related activities automatically
  342. file.source = 'import';
  343. if (error) {
  344. throw error;
  345. } else {
  346. const wekanAtt = Attachments.insert(file, () => {
  347. // we do nothing
  348. });
  349. self.attachmentIds[att.id] = wekanAtt._id;
  350. //
  351. if (trelloCoverId === att.id) {
  352. Cards.direct.update(cardId, {
  353. $set: { coverId: wekanAtt._id },
  354. });
  355. }
  356. }
  357. });
  358. }
  359. // todo XXX set cover - if need be
  360. });
  361. }
  362. result.push(cardId);
  363. });
  364. return result;
  365. }
  366. // Create labels if they do not exist and load this.labels.
  367. createLabels(trelloLabels, board) {
  368. trelloLabels.forEach(label => {
  369. const color = label.color;
  370. const name = label.name;
  371. const existingLabel = board.getLabel(name, color);
  372. if (existingLabel) {
  373. this.labels[label.id] = existingLabel._id;
  374. } else {
  375. const idLabelCreated = board.pushLabel(name, color);
  376. this.labels[label.id] = idLabelCreated;
  377. }
  378. });
  379. }
  380. createLists(trelloLists, boardId) {
  381. trelloLists.forEach(list => {
  382. const listToCreate = {
  383. archived: list.closed,
  384. boardId,
  385. // We are being defensing here by providing a default date (now) if the
  386. // creation date wasn't found on the action log. This happen on old
  387. // Trello boards (eg from 2013) that didn't log the 'createList' action
  388. // we require.
  389. createdAt: this._now(this.createdAt.lists[list.id]),
  390. title: list.name,
  391. sort: list.pos,
  392. };
  393. const listId = Lists.direct.insert(listToCreate);
  394. Lists.direct.update(listId, { $set: { updatedAt: this._now() } });
  395. this.lists[list.id] = listId;
  396. // log activity
  397. // Activities.direct.insert({
  398. // activityType: 'importList',
  399. // boardId,
  400. // createdAt: this._now(),
  401. // listId,
  402. // source: {
  403. // id: list.id,
  404. // system: 'Trello',
  405. // },
  406. // // We attribute the import to current user,
  407. // // not the creator of the original object
  408. // userId: this._user(),
  409. // });
  410. });
  411. }
  412. createSwimlanes(boardId) {
  413. const swimlaneToCreate = {
  414. archived: false,
  415. boardId,
  416. // We are being defensing here by providing a default date (now) if the
  417. // creation date wasn't found on the action log. This happen on old
  418. // Wekan boards (eg from 2013) that didn't log the 'createList' action
  419. // we require.
  420. createdAt: this._now(),
  421. title: 'Default',
  422. sort: 1,
  423. };
  424. const swimlaneId = Swimlanes.direct.insert(swimlaneToCreate);
  425. Swimlanes.direct.update(swimlaneId, { $set: { updatedAt: this._now() } });
  426. this.swimlane = swimlaneId;
  427. }
  428. createChecklists(trelloChecklists) {
  429. trelloChecklists.forEach(checklist => {
  430. if (this.cards[checklist.idCard]) {
  431. // Create the checklist
  432. const checklistToCreate = {
  433. cardId: this.cards[checklist.idCard],
  434. title: checklist.name,
  435. createdAt: this._now(),
  436. sort: checklist.pos,
  437. };
  438. const checklistId = Checklists.direct.insert(checklistToCreate);
  439. // keep track of Trello id => Wekan id
  440. this.checklists[checklist.id] = checklistId;
  441. // Now add the items to the checklistItems
  442. let counter = 0;
  443. checklist.checkItems.forEach(item => {
  444. counter++;
  445. const checklistItemTocreate = {
  446. _id: checklistId + counter,
  447. title: item.name,
  448. checklistId: this.checklists[checklist.id],
  449. cardId: this.cards[checklist.idCard],
  450. sort: item.pos,
  451. isFinished: item.state === 'complete',
  452. };
  453. ChecklistItems.direct.insert(checklistItemTocreate);
  454. });
  455. }
  456. });
  457. }
  458. getAdmin(trelloMemberType) {
  459. return trelloMemberType === 'admin';
  460. }
  461. getColor(trelloColorCode) {
  462. // trello color name => wekan color
  463. const mapColors = {
  464. blue: 'belize',
  465. orange: 'pumpkin',
  466. green: 'nephritis',
  467. red: 'pomegranate',
  468. purple: 'wisteria',
  469. pink: 'moderatepink',
  470. lime: 'limegreen',
  471. sky: 'strongcyan',
  472. grey: 'midnight',
  473. };
  474. const wekanColor = mapColors[trelloColorCode];
  475. return wekanColor || Boards.simpleSchema()._schema.color.allowedValues[0];
  476. }
  477. getPermission(trelloPermissionCode) {
  478. if (trelloPermissionCode === 'public') {
  479. return 'public';
  480. }
  481. // Wekan does NOT have organization level, so we default both 'private' and
  482. // 'org' to private.
  483. return 'private';
  484. }
  485. parseActions(trelloActions) {
  486. trelloActions.forEach(action => {
  487. if (action.type === 'addAttachmentToCard') {
  488. // We have to be cautious, because the attachment could have been removed later.
  489. // In that case Trello still reports its addition, but removes its 'url' field.
  490. // So we test for that
  491. const trelloAttachment = action.data.attachment;
  492. // We need the idMemberCreator
  493. trelloAttachment.idMemberCreator = action.idMemberCreator;
  494. if (trelloAttachment.url) {
  495. // we cannot actually create the Wekan attachment, because we don't yet
  496. // have the cards to attach it to, so we store it in the instance variable.
  497. const trelloCardId = action.data.card.id;
  498. if (!this.attachments[trelloCardId]) {
  499. this.attachments[trelloCardId] = [];
  500. }
  501. this.attachments[trelloCardId].push(trelloAttachment);
  502. }
  503. } else if (action.type === 'commentCard') {
  504. const id = action.data.card.id;
  505. if (this.comments[id]) {
  506. this.comments[id].push(action);
  507. } else {
  508. this.comments[id] = [action];
  509. }
  510. } else if (action.type === 'createBoard') {
  511. this.createdAt.board = action.date;
  512. } else if (action.type === 'createCard') {
  513. const cardId = action.data.card.id;
  514. this.createdAt.cards[cardId] = action.date;
  515. this.createdBy.cards[cardId] = action.idMemberCreator;
  516. } else if (action.type === 'createList') {
  517. const listId = action.data.list.id;
  518. this.createdAt.lists[listId] = action.date;
  519. }
  520. });
  521. }
  522. importActions(actions, boardId) {
  523. actions.forEach(action => {
  524. switch (action.type) {
  525. // Board related actions
  526. // TODO: addBoardMember, removeBoardMember
  527. case 'createBoard': {
  528. Activities.direct.insert({
  529. userId: this._user(action.idMemberCreator),
  530. type: 'board',
  531. activityTypeId: boardId,
  532. activityType: 'createBoard',
  533. boardId,
  534. createdAt: this._now(action.date),
  535. });
  536. break;
  537. }
  538. // List related activities
  539. // TODO: removeList, archivedList
  540. case 'createList': {
  541. Activities.direct.insert({
  542. userId: this._user(action.idMemberCreator),
  543. type: 'list',
  544. activityType: 'createList',
  545. listId: this.lists[action.data.list.id],
  546. boardId,
  547. createdAt: this._now(action.date),
  548. });
  549. break;
  550. }
  551. // Card related activities
  552. // TODO: archivedCard, restoredCard, joinMember, unjoinMember
  553. case 'createCard': {
  554. Activities.direct.insert({
  555. userId: this._user(action.idMemberCreator),
  556. activityType: 'createCard',
  557. listId: this.lists[action.data.list.id],
  558. cardId: this.cards[action.data.card.id],
  559. boardId,
  560. createdAt: this._now(action.date),
  561. });
  562. break;
  563. }
  564. case 'updateCard': {
  565. if (action.data.old.idList) {
  566. Activities.direct.insert({
  567. userId: this._user(action.idMemberCreator),
  568. oldListId: this.lists[action.data.old.idList],
  569. activityType: 'moveCard',
  570. listId: this.lists[action.data.listAfter.id],
  571. cardId: this.cards[action.data.card.id],
  572. boardId,
  573. createdAt: this._now(action.date),
  574. });
  575. }
  576. break;
  577. }
  578. // Comment related activities
  579. // Trello doesn't export the comment id
  580. // Attachment related activities
  581. case 'addAttachmentToCard': {
  582. Activities.direct.insert({
  583. userId: this._user(action.idMemberCreator),
  584. type: 'card',
  585. activityType: 'addAttachment',
  586. attachmentId: this.attachmentIds[action.data.attachment.id],
  587. cardId: this.cards[action.data.card.id],
  588. boardId,
  589. createdAt: this._now(action.date),
  590. });
  591. break;
  592. }
  593. // Checklist related activities
  594. case 'addChecklistToCard': {
  595. Activities.direct.insert({
  596. userId: this._user(action.idMemberCreator),
  597. activityType: 'addChecklist',
  598. cardId: this.cards[action.data.card.id],
  599. checklistId: this.checklists[action.data.checklist.id],
  600. boardId,
  601. createdAt: this._now(action.date),
  602. });
  603. break;
  604. }
  605. }
  606. // Trello doesn't have an add checklist item action
  607. });
  608. }
  609. check(board) {
  610. try {
  611. // check(data, {
  612. // membersMapping: Match.Optional(Object),
  613. // });
  614. this.checkActions(board.actions);
  615. this.checkBoard(board);
  616. this.checkLabels(board.labels);
  617. this.checkLists(board.lists);
  618. this.checkCards(board.cards);
  619. this.checkChecklists(board.checklists);
  620. } catch (e) {
  621. throw new Meteor.Error('error-json-schema');
  622. }
  623. }
  624. create(board, currentBoardId) {
  625. // TODO : Make isSandstorm variable global
  626. const isSandstorm =
  627. Meteor.settings &&
  628. Meteor.settings.public &&
  629. Meteor.settings.public.sandstorm;
  630. if (isSandstorm && currentBoardId) {
  631. const currentBoard = Boards.findOne(currentBoardId);
  632. currentBoard.archive();
  633. }
  634. this.parseActions(board.actions);
  635. const boardId = this.createBoardAndLabels(board);
  636. this.createLists(board.lists, boardId);
  637. this.createSwimlanes(boardId);
  638. this.createCards(board.cards, boardId);
  639. this.createChecklists(board.checklists);
  640. this.importActions(board.actions, boardId);
  641. // XXX add members
  642. return boardId;
  643. }
  644. }