trelloCreator.js 16 KB

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