import.js 14 KB

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