2
0

trelloCreator.js 20 KB

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