trelloCreator.js 20 KB

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