import.js 16 KB

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