trelloCreator.js 21 KB

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