import.js 15 KB

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