trelloCreator.js 20 KB

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