trelloCreator.js 21 KB

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