import.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. const DateString = Match.Where(function (dateAsString) {
  2. check(dateAsString, String);
  3. return moment(dateAsString, moment.ISO_8601).isValid();
  4. });
  5. 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. }],
  137. permission: this.getPermission(trelloBoard.prefs.permissionLevel),
  138. slug: getSlug(trelloBoard.name) || 'board',
  139. stars: 0,
  140. title: trelloBoard.name,
  141. };
  142. // now add other members
  143. if(trelloBoard.memberships) {
  144. trelloBoard.memberships.forEach((trelloMembership) => {
  145. const trelloId = trelloMembership.idMember;
  146. // do we have a mapping?
  147. if(this.members[trelloId]) {
  148. const wekanId = this.members[trelloId];
  149. // do we already have it in our list?
  150. const wekanMember = boardToCreate.members.find((wekanMember) => wekanMember.userId === wekanId);
  151. if(wekanMember) {
  152. // we're already mapped, but maybe with lower rights
  153. if(!wekanMember.isAdmin) {
  154. wekanMember.isAdmin = this.getAdmin(trelloMembership.memberType);
  155. }
  156. } else {
  157. boardToCreate.members.push({
  158. userId: wekanId,
  159. isAdmin: this.getAdmin(trelloMembership.memberType),
  160. isActive: true,
  161. });
  162. }
  163. }
  164. });
  165. }
  166. trelloBoard.labels.forEach((label) => {
  167. const labelToCreate = {
  168. _id: Random.id(6),
  169. color: label.color,
  170. name: label.name,
  171. };
  172. // We need to remember them by Trello ID, as this is the only ref we have
  173. // when importing cards.
  174. this.labels[label.id] = labelToCreate._id;
  175. boardToCreate.labels.push(labelToCreate);
  176. });
  177. const boardId = Boards.direct.insert(boardToCreate);
  178. Boards.direct.update(boardId, {$set: {modifiedAt: this._now()}});
  179. // log activity
  180. Activities.direct.insert({
  181. activityType: 'importBoard',
  182. boardId,
  183. createdAt: this._now(),
  184. source: {
  185. id: trelloBoard.id,
  186. system: 'Trello',
  187. url: trelloBoard.url,
  188. },
  189. // We attribute the import to current user,
  190. // not the author from the original object.
  191. userId: this._user(),
  192. });
  193. return boardId;
  194. }
  195. /**
  196. * Create the Wekan cards corresponding to the supplied Trello cards,
  197. * as well as all linked data: activities, comments, and attachments
  198. * @param trelloCards
  199. * @param boardId
  200. * @returns {Array}
  201. */
  202. createCards(trelloCards, boardId) {
  203. const result = [];
  204. trelloCards.forEach((card) => {
  205. const cardToCreate = {
  206. archived: card.closed,
  207. boardId,
  208. // very old boards won't have a creation activity so no creation date
  209. createdAt: this._now(this.createdAt.cards[card.id]),
  210. dateLastActivity: this._now(),
  211. description: card.desc,
  212. listId: this.lists[card.idList],
  213. sort: card.pos,
  214. title: card.name,
  215. // we attribute the card to its creator if available
  216. userId: this._user(this.createdBy.cards[card.id]),
  217. };
  218. // add labels
  219. if (card.idLabels) {
  220. cardToCreate.labelIds = card.idLabels.map((trelloId) => {
  221. return this.labels[trelloId];
  222. });
  223. }
  224. // add members {
  225. if(card.idMembers) {
  226. const wekanMembers = [];
  227. // we can't just map, as some members may not have been mapped
  228. card.idMembers.forEach((trelloId) => {
  229. if(this.members[trelloId]) {
  230. const wekanId = this.members[trelloId];
  231. // we may map multiple Trello members to the same wekan user
  232. // in which case we risk adding the same user multiple times
  233. if(!wekanMembers.find((wId) => wId === wekanId)){
  234. wekanMembers.push(wekanId);
  235. }
  236. }
  237. return true;
  238. });
  239. if(wekanMembers.length>0) {
  240. cardToCreate.members = wekanMembers;
  241. }
  242. }
  243. // insert card
  244. const cardId = Cards.direct.insert(cardToCreate);
  245. // keep track of Trello id => WeKan id
  246. this.cards[card.id] = cardId;
  247. // log activity
  248. Activities.direct.insert({
  249. activityType: 'importCard',
  250. boardId,
  251. cardId,
  252. createdAt: this._now(),
  253. listId: cardToCreate.listId,
  254. source: {
  255. id: card.id,
  256. system: 'Trello',
  257. url: card.url,
  258. },
  259. // we attribute the import to current user,
  260. // not the author of the original card
  261. userId: this._user(),
  262. });
  263. // add comments
  264. const comments = this.comments[card.id];
  265. if (comments) {
  266. comments.forEach((comment) => {
  267. const commentToCreate = {
  268. boardId,
  269. cardId,
  270. createdAt: this._now(comment.date),
  271. text: comment.data.text,
  272. // we attribute the comment to the original author, default to current user
  273. userId: this._user(comment.memberCreator.id),
  274. };
  275. // dateLastActivity will be set from activity insert, no need to
  276. // update it ourselves
  277. const commentId = CardComments.direct.insert(commentToCreate);
  278. Activities.direct.insert({
  279. activityType: 'addComment',
  280. boardId: commentToCreate.boardId,
  281. cardId: commentToCreate.cardId,
  282. commentId,
  283. createdAt: this._now(commentToCreate.createdAt),
  284. // we attribute the addComment (not the import)
  285. // to the original author - it is needed by some UI elements.
  286. userId: this._user(commentToCreate.userId),
  287. });
  288. });
  289. }
  290. const attachments = this.attachments[card.id];
  291. const trelloCoverId = card.idAttachmentCover;
  292. if (attachments) {
  293. attachments.forEach((att) => {
  294. const file = new FS.File();
  295. // Simulating file.attachData on the client generates multiple errors
  296. // - HEAD returns null, which causes exception down the line
  297. // - the template then tries to display the url to the attachment which causes other errors
  298. // so we make it server only, and let UI catch up once it is done, forget about latency comp.
  299. if(Meteor.isServer) {
  300. file.attachData(att.url, function (error) {
  301. file.boardId = boardId;
  302. file.cardId = cardId;
  303. if (error) {
  304. throw(error);
  305. } else {
  306. const wekanAtt = Attachments.insert(file, () => {
  307. // we do nothing
  308. });
  309. //
  310. if(trelloCoverId === att.id) {
  311. Cards.direct.update(cardId, { $set: {coverId: wekanAtt._id}});
  312. }
  313. }
  314. });
  315. }
  316. // todo XXX set cover - if need be
  317. });
  318. }
  319. result.push(cardId);
  320. });
  321. return result;
  322. }
  323. // Create labels if they do not exist and load this.labels.
  324. createLabels(trelloLabels, board) {
  325. trelloLabels.forEach((label) => {
  326. const color = label.color;
  327. const name = label.name;
  328. const existingLabel = board.getLabel(name, color);
  329. if (existingLabel) {
  330. this.labels[label.id] = existingLabel._id;
  331. } else {
  332. const idLabelCreated = board.pushLabel(name, color);
  333. this.labels[label.id] = idLabelCreated;
  334. }
  335. });
  336. }
  337. createLists(trelloLists, boardId) {
  338. trelloLists.forEach((list) => {
  339. const listToCreate = {
  340. archived: list.closed,
  341. boardId,
  342. // We are being defensing here by providing a default date (now) if the
  343. // creation date wasn't found on the action log. This happen on old
  344. // Trello boards (eg from 2013) that didn't log the 'createList' action
  345. // we require.
  346. createdAt: this._now(this.createdAt.lists[list.id]),
  347. title: list.name,
  348. };
  349. const listId = Lists.direct.insert(listToCreate);
  350. Lists.direct.update(listId, {$set: {'updatedAt': this._now()}});
  351. this.lists[list.id] = listId;
  352. // log activity
  353. Activities.direct.insert({
  354. activityType: 'importList',
  355. boardId,
  356. createdAt: this._now(),
  357. listId,
  358. source: {
  359. id: list.id,
  360. system: 'Trello',
  361. },
  362. // We attribute the import to current user,
  363. // not the creator of the original object
  364. userId: this._user(),
  365. });
  366. });
  367. }
  368. createChecklists(trelloChecklists) {
  369. trelloChecklists.forEach((checklist) => {
  370. // Create the checklist
  371. const checklistToCreate = {
  372. cardId: this.cards[checklist.idCard],
  373. title: checklist.name,
  374. createdAt: this._now(),
  375. };
  376. const checklistId = Checklists.direct.insert(checklistToCreate);
  377. // Now add the items to the checklist
  378. const itemsToCreate = [];
  379. checklist.checkItems.forEach((item) => {
  380. itemsToCreate.push({
  381. _id: checklistId + itemsToCreate.length,
  382. title: item.name,
  383. isFinished: item.state === 'complete',
  384. });
  385. });
  386. Checklists.direct.update(checklistId, {$set: {items: itemsToCreate}});
  387. });
  388. }
  389. getAdmin(trelloMemberType) {
  390. return trelloMemberType === 'admin';
  391. }
  392. getColor(trelloColorCode) {
  393. // trello color name => wekan color
  394. const mapColors = {
  395. 'blue': 'belize',
  396. 'orange': 'pumpkin',
  397. 'green': 'nephritis',
  398. 'red': 'pomegranate',
  399. 'purple': 'wisteria',
  400. 'pink': 'pomegranate',
  401. 'lime': 'nephritis',
  402. 'sky': 'belize',
  403. 'grey': 'midnight',
  404. };
  405. const wekanColor = mapColors[trelloColorCode];
  406. return wekanColor || Boards.simpleSchema()._schema.color.allowedValues[0];
  407. }
  408. getPermission(trelloPermissionCode) {
  409. if (trelloPermissionCode === 'public') {
  410. return 'public';
  411. }
  412. // Wekan does NOT have organization level, so we default both 'private' and
  413. // 'org' to private.
  414. return 'private';
  415. }
  416. parseActions(trelloActions) {
  417. trelloActions.forEach((action) => {
  418. if (action.type === 'addAttachmentToCard') {
  419. // We have to be cautious, because the attachment could have been removed later.
  420. // In that case Trello still reports its addition, but removes its 'url' field.
  421. // So we test for that
  422. const trelloAttachment = action.data.attachment;
  423. if(trelloAttachment.url) {
  424. // we cannot actually create the Wekan attachment, because we don't yet
  425. // have the cards to attach it to, so we store it in the instance variable.
  426. const trelloCardId = action.data.card.id;
  427. if(!this.attachments[trelloCardId]) {
  428. this.attachments[trelloCardId] = [];
  429. }
  430. this.attachments[trelloCardId].push(trelloAttachment);
  431. }
  432. } else if (action.type === 'commentCard') {
  433. const id = action.data.card.id;
  434. if (this.comments[id]) {
  435. this.comments[id].push(action);
  436. } else {
  437. this.comments[id] = [action];
  438. }
  439. } else if (action.type === 'createBoard') {
  440. this.createdAt.board = action.date;
  441. } else if (action.type === 'createCard') {
  442. const cardId = action.data.card.id;
  443. this.createdAt.cards[cardId] = action.date;
  444. this.createdBy.cards[cardId] = action.idMemberCreator;
  445. } else if (action.type === 'createList') {
  446. const listId = action.data.list.id;
  447. this.createdAt.lists[listId] = action.date;
  448. }
  449. });
  450. }
  451. }
  452. Meteor.methods({
  453. importTrelloBoard(trelloBoard, data) {
  454. const trelloCreator = new TrelloCreator(data);
  455. // 1. check all parameters are ok from a syntax point of view
  456. try {
  457. check(data, {
  458. membersMapping: Match.Optional(Object),
  459. });
  460. trelloCreator.checkActions(trelloBoard.actions);
  461. trelloCreator.checkBoard(trelloBoard);
  462. trelloCreator.checkLabels(trelloBoard.labels);
  463. trelloCreator.checkLists(trelloBoard.lists);
  464. trelloCreator.checkCards(trelloBoard.cards);
  465. trelloCreator.checkChecklists(trelloBoard.checklists);
  466. } catch (e) {
  467. throw new Meteor.Error('error-json-schema');
  468. }
  469. // 2. check parameters are ok from a business point of view (exist &
  470. // authorized) nothing to check, everyone can import boards in their account
  471. // 3. create all elements
  472. trelloCreator.parseActions(trelloBoard.actions);
  473. const boardId = trelloCreator.createBoardAndLabels(trelloBoard);
  474. trelloCreator.createLists(trelloBoard.lists, boardId);
  475. trelloCreator.createCards(trelloBoard.cards, boardId);
  476. trelloCreator.createChecklists(trelloBoard.checklists);
  477. // XXX add members
  478. return boardId;
  479. },
  480. });