import.js 15 KB

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