boards.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. Boards = new Mongo.Collection('boards');
  2. Boards.attachSchema(new SimpleSchema({
  3. title: {
  4. type: String,
  5. },
  6. slug: {
  7. type: String,
  8. autoValue() { // eslint-disable-line consistent-return
  9. // XXX We need to improve slug management. Only the id should be necessary
  10. // to identify a board in the code.
  11. // XXX If the board title is updated, the slug should also be updated.
  12. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  13. // return an empty string. This is causes bugs in our application so we set
  14. // a default slug in this case.
  15. if (this.isInsert && !this.isSet) {
  16. let slug = 'board';
  17. const title = this.field('title');
  18. if (title.isSet) {
  19. slug = getSlug(title.value) || slug;
  20. }
  21. return slug;
  22. }
  23. },
  24. },
  25. archived: {
  26. type: Boolean,
  27. autoValue() { // eslint-disable-line consistent-return
  28. if (this.isInsert && !this.isSet) {
  29. return false;
  30. }
  31. },
  32. },
  33. createdAt: {
  34. type: Date,
  35. autoValue() { // eslint-disable-line consistent-return
  36. if (this.isInsert) {
  37. return new Date();
  38. } else {
  39. this.unset();
  40. }
  41. },
  42. },
  43. // XXX Inconsistent field naming
  44. modifiedAt: {
  45. type: Date,
  46. optional: true,
  47. autoValue() { // eslint-disable-line consistent-return
  48. if (this.isUpdate) {
  49. return new Date();
  50. } else {
  51. this.unset();
  52. }
  53. },
  54. },
  55. // De-normalized number of users that have starred this board
  56. stars: {
  57. type: Number,
  58. autoValue() { // eslint-disable-line consistent-return
  59. if (this.isInsert) {
  60. return 0;
  61. }
  62. },
  63. },
  64. // De-normalized label system
  65. 'labels': {
  66. type: [Object],
  67. autoValue() { // eslint-disable-line consistent-return
  68. if (this.isInsert && !this.isSet) {
  69. const colors = Boards.simpleSchema()._schema['labels.$.color'].allowedValues;
  70. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  71. return defaultLabelsColors.map((color) => ({
  72. color,
  73. _id: Random.id(6),
  74. name: '',
  75. }));
  76. }
  77. },
  78. },
  79. 'labels.$._id': {
  80. // We don't specify that this field must be unique in the board because that
  81. // will cause performance penalties and is not necessary since this field is
  82. // always set on the server.
  83. // XXX Actually if we create a new label, the `_id` is set on the client
  84. // without being overwritten by the server, could it be a problem?
  85. type: String,
  86. },
  87. 'labels.$.name': {
  88. type: String,
  89. optional: true,
  90. },
  91. 'labels.$.color': {
  92. type: String,
  93. allowedValues: [
  94. 'green', 'yellow', 'orange', 'red', 'purple',
  95. 'blue', 'sky', 'lime', 'pink', 'black',
  96. ],
  97. },
  98. // XXX We might want to maintain more informations under the member sub-
  99. // documents like de-normalized meta-data (the date the member joined the
  100. // board, the number of contributions, etc.).
  101. 'members': {
  102. type: [Object],
  103. autoValue() { // eslint-disable-line consistent-return
  104. if (this.isInsert && !this.isSet) {
  105. return [{
  106. userId: this.userId,
  107. isAdmin: true,
  108. isActive: true,
  109. isCommentOnly: false,
  110. }];
  111. }
  112. },
  113. },
  114. 'members.$.userId': {
  115. type: String,
  116. },
  117. 'members.$.isAdmin': {
  118. type: Boolean,
  119. },
  120. 'members.$.isActive': {
  121. type: Boolean,
  122. },
  123. 'members.$.isCommentOnly': {
  124. type: Boolean,
  125. },
  126. permission: {
  127. type: String,
  128. allowedValues: ['public', 'private'],
  129. },
  130. color: {
  131. type: String,
  132. allowedValues: [
  133. 'belize',
  134. 'nephritis',
  135. 'pomegranate',
  136. 'pumpkin',
  137. 'wisteria',
  138. 'midnight',
  139. ],
  140. autoValue() { // eslint-disable-line consistent-return
  141. if (this.isInsert && !this.isSet) {
  142. return Boards.simpleSchema()._schema.color.allowedValues[0];
  143. }
  144. },
  145. },
  146. description: {
  147. type: String,
  148. optional: true,
  149. },
  150. }));
  151. Boards.helpers({
  152. /**
  153. * Is supplied user authorized to view this board?
  154. */
  155. isVisibleBy(user) {
  156. if (this.isPublic()) {
  157. // public boards are visible to everyone
  158. return true;
  159. } else {
  160. // otherwise you have to be logged-in and active member
  161. return user && this.isActiveMember(user._id);
  162. }
  163. },
  164. /**
  165. * Is the user one of the active members of the board?
  166. *
  167. * @param userId
  168. * @returns {boolean} the member that matches, or undefined/false
  169. */
  170. isActiveMember(userId) {
  171. if (userId) {
  172. return this.members.find((member) => (member.userId === userId && member.isActive));
  173. } else {
  174. return false;
  175. }
  176. },
  177. isPublic() {
  178. return this.permission === 'public';
  179. },
  180. lists() {
  181. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 } });
  182. },
  183. activities() {
  184. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 } });
  185. },
  186. activeMembers() {
  187. return _.where(this.members, { isActive: true });
  188. },
  189. activeAdmins() {
  190. return _.where(this.members, { isActive: true, isAdmin: true });
  191. },
  192. memberUsers() {
  193. return Users.find({ _id: { $in: _.pluck(this.members, 'userId') } });
  194. },
  195. getLabel(name, color) {
  196. return _.findWhere(this.labels, { name, color });
  197. },
  198. labelIndex(labelId) {
  199. return _.pluck(this.labels, '_id').indexOf(labelId);
  200. },
  201. memberIndex(memberId) {
  202. return _.pluck(this.members, 'userId').indexOf(memberId);
  203. },
  204. hasMember(memberId) {
  205. return !!_.findWhere(this.members, { userId: memberId, isActive: true });
  206. },
  207. hasAdmin(memberId) {
  208. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: true });
  209. },
  210. hasCommentOnly(memberId) {
  211. return !!_.findWhere(this.members, { userId: memberId, isActive: true, isAdmin: false, isCommentOnly: true });
  212. },
  213. absoluteUrl() {
  214. return FlowRouter.url('board', { id: this._id, slug: this.slug });
  215. },
  216. colorClass() {
  217. return `board-color-${this.color}`;
  218. },
  219. // XXX currently mutations return no value so we have an issue when using addLabel in import
  220. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  221. pushLabel(name, color) {
  222. const _id = Random.id(6);
  223. Boards.direct.update(this._id, { $push: { labels: { _id, name, color } } });
  224. return _id;
  225. },
  226. });
  227. Boards.mutations({
  228. archive() {
  229. return { $set: { archived: true } };
  230. },
  231. restore() {
  232. return { $set: { archived: false } };
  233. },
  234. rename(title) {
  235. return { $set: { title } };
  236. },
  237. setDescription(description) {
  238. return { $set: { description } };
  239. },
  240. setColor(color) {
  241. return { $set: { color } };
  242. },
  243. setVisibility(visibility) {
  244. return { $set: { permission: visibility } };
  245. },
  246. addLabel(name, color) {
  247. // If label with the same name and color already exists we don't want to
  248. // create another one because they would be indistinguishable in the UI
  249. // (they would still have different `_id` but that is not exposed to the
  250. // user).
  251. if (!this.getLabel(name, color)) {
  252. const _id = Random.id(6);
  253. return { $push: { labels: { _id, name, color } } };
  254. }
  255. return {};
  256. },
  257. editLabel(labelId, name, color) {
  258. if (!this.getLabel(name, color)) {
  259. const labelIndex = this.labelIndex(labelId);
  260. return {
  261. $set: {
  262. [`labels.${labelIndex}.name`]: name,
  263. [`labels.${labelIndex}.color`]: color,
  264. },
  265. };
  266. }
  267. return {};
  268. },
  269. removeLabel(labelId) {
  270. return { $pull: { labels: { _id: labelId } } };
  271. },
  272. changeOwnership(fromId, toId) {
  273. const memberIndex = this.memberIndex(fromId);
  274. return {
  275. $set: {
  276. [`members.${memberIndex}.userId`]: toId,
  277. },
  278. };
  279. },
  280. addMember(memberId) {
  281. const memberIndex = this.memberIndex(memberId);
  282. if (memberIndex >= 0) {
  283. return {
  284. $set: {
  285. [`members.${memberIndex}.isActive`]: true,
  286. },
  287. };
  288. }
  289. return {
  290. $push: {
  291. members: {
  292. userId: memberId,
  293. isAdmin: false,
  294. isActive: true,
  295. isCommentOnly: false,
  296. },
  297. },
  298. };
  299. },
  300. removeMember(memberId) {
  301. const memberIndex = this.memberIndex(memberId);
  302. // we do not allow the only one admin to be removed
  303. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  304. if (!allowRemove) {
  305. return {
  306. $set: {
  307. [`members.${memberIndex}.isActive`]: true,
  308. },
  309. };
  310. }
  311. return {
  312. $set: {
  313. [`members.${memberIndex}.isActive`]: false,
  314. [`members.${memberIndex}.isAdmin`]: false,
  315. },
  316. };
  317. },
  318. setMemberPermission(memberId, isAdmin, isCommentOnly) {
  319. const memberIndex = this.memberIndex(memberId);
  320. // do not allow change permission of self
  321. if (memberId === Meteor.userId()) {
  322. isAdmin = this.members[memberIndex].isAdmin;
  323. }
  324. return {
  325. $set: {
  326. [`members.${memberIndex}.isAdmin`]: isAdmin,
  327. [`members.${memberIndex}.isCommentOnly`]: isCommentOnly,
  328. },
  329. };
  330. },
  331. });
  332. if (Meteor.isServer) {
  333. Boards.allow({
  334. insert: Meteor.userId,
  335. update: allowIsBoardAdmin,
  336. remove: allowIsBoardAdmin,
  337. fetch: ['members'],
  338. });
  339. // The number of users that have starred this board is managed by trusted code
  340. // and the user is not allowed to update it
  341. Boards.deny({
  342. update(userId, board, fieldNames) {
  343. return _.contains(fieldNames, 'stars');
  344. },
  345. fetch: [],
  346. });
  347. // We can't remove a member if it is the last administrator
  348. Boards.deny({
  349. update(userId, doc, fieldNames, modifier) {
  350. if (!_.contains(fieldNames, 'members'))
  351. return false;
  352. // We only care in case of a $pull operation, ie remove a member
  353. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  354. return false;
  355. // If there is more than one admin, it's ok to remove anyone
  356. const nbAdmins = _.where(doc.members, { isActive: true, isAdmin: true }).length;
  357. if (nbAdmins > 1)
  358. return false;
  359. // If all the previous conditions were verified, we can't remove
  360. // a user if it's an admin
  361. const removedMemberId = modifier.$pull.members.userId;
  362. return Boolean(_.findWhere(doc.members, {
  363. userId: removedMemberId,
  364. isAdmin: true,
  365. }));
  366. },
  367. fetch: ['members'],
  368. });
  369. Meteor.methods({
  370. quitBoard(boardId) {
  371. check(boardId, String);
  372. const board = Boards.findOne(boardId);
  373. if (board) {
  374. const userId = Meteor.userId();
  375. const index = board.memberIndex(userId);
  376. if (index >= 0) {
  377. board.removeMember(userId);
  378. return true;
  379. } else throw new Meteor.Error('error-board-notAMember');
  380. } else throw new Meteor.Error('error-board-doesNotExist');
  381. },
  382. });
  383. }
  384. if (Meteor.isServer) {
  385. // Let MongoDB ensure that a member is not included twice in the same board
  386. Meteor.startup(() => {
  387. Boards._collection._ensureIndex({
  388. _id: 1,
  389. 'members.userId': 1,
  390. }, { unique: true });
  391. Boards._collection._ensureIndex({ 'members.userId': 1 });
  392. });
  393. // Genesis: the first activity of the newly created board
  394. Boards.after.insert((userId, doc) => {
  395. Activities.insert({
  396. userId,
  397. type: 'board',
  398. activityTypeId: doc._id,
  399. activityType: 'createBoard',
  400. boardId: doc._id,
  401. });
  402. });
  403. // If the user remove one label from a board, we cant to remove reference of
  404. // this label in any card of this board.
  405. Boards.after.update((userId, doc, fieldNames, modifier) => {
  406. if (!_.contains(fieldNames, 'labels') ||
  407. !modifier.$pull ||
  408. !modifier.$pull.labels ||
  409. !modifier.$pull.labels._id) {
  410. return;
  411. }
  412. const removedLabelId = modifier.$pull.labels._id;
  413. Cards.update(
  414. { boardId: doc._id },
  415. {
  416. $pull: {
  417. labelIds: removedLabelId,
  418. },
  419. },
  420. { multi: true }
  421. );
  422. });
  423. const foreachRemovedMember = (doc, modifier, callback) => {
  424. Object.keys(modifier).forEach((set) => {
  425. if (modifier[set] !== false) {
  426. return;
  427. }
  428. const parts = set.split('.');
  429. if (parts.length === 3 && parts[0] === 'members' && parts[2] === 'isActive') {
  430. callback(doc.members[parts[1]].userId);
  431. }
  432. });
  433. };
  434. // Remove a member from all objects of the board before leaving the board
  435. Boards.before.update((userId, doc, fieldNames, modifier) => {
  436. if (!_.contains(fieldNames, 'members')) {
  437. return;
  438. }
  439. if (modifier.$set) {
  440. const boardId = doc._id;
  441. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  442. Cards.update(
  443. { boardId },
  444. {
  445. $pull: {
  446. members: memberId,
  447. watchers: memberId,
  448. },
  449. },
  450. { multi: true }
  451. );
  452. Lists.update(
  453. { boardId },
  454. {
  455. $pull: {
  456. watchers: memberId,
  457. },
  458. },
  459. { multi: true }
  460. );
  461. const board = Boards._transform(doc);
  462. board.setWatcher(memberId, false);
  463. // Remove board from users starred list
  464. if (!board.isPublic()) {
  465. Users.update(
  466. memberId,
  467. {
  468. $pull: {
  469. 'profile.starredBoards': boardId,
  470. },
  471. }
  472. );
  473. }
  474. });
  475. }
  476. });
  477. // Add a new activity if we add or remove a member to the board
  478. Boards.after.update((userId, doc, fieldNames, modifier) => {
  479. if (!_.contains(fieldNames, 'members')) {
  480. return;
  481. }
  482. // Say hello to the new member
  483. if (modifier.$push && modifier.$push.members) {
  484. const memberId = modifier.$push.members.userId;
  485. Activities.insert({
  486. userId,
  487. memberId,
  488. type: 'member',
  489. activityType: 'addBoardMember',
  490. boardId: doc._id,
  491. });
  492. }
  493. // Say goodbye to the former member
  494. if (modifier.$set) {
  495. foreachRemovedMember(doc, modifier.$set, (memberId) => {
  496. Activities.insert({
  497. userId,
  498. memberId,
  499. type: 'member',
  500. activityType: 'removeBoardMember',
  501. boardId: doc._id,
  502. });
  503. });
  504. }
  505. });
  506. }
  507. //BOARDS REST API
  508. if (Meteor.isServer) {
  509. JsonRoutes.add('GET', '/api/users/:userId/boards', function (req, res, next) {
  510. try {
  511. Authentication.checkLoggedIn(req.userId);
  512. const paramUserId = req.params.userId;
  513. // A normal user should be able to see their own boards,
  514. // admins can access boards of any user
  515. Authentication.checkAdminOrCondition(req.userId, req.userId === paramUserId);
  516. const data = Boards.find({
  517. archived: false,
  518. 'members.userId': paramUserId,
  519. }, {
  520. sort: ['title'],
  521. }).map(function(board) {
  522. return {
  523. _id: board._id,
  524. title: board.title,
  525. };
  526. });
  527. JsonRoutes.sendResult(res, {code: 200, data});
  528. }
  529. catch (error) {
  530. JsonRoutes.sendResult(res, {
  531. code: 200,
  532. data: error,
  533. });
  534. }
  535. });
  536. JsonRoutes.add('GET', '/api/boards', function (req, res, next) {
  537. try {
  538. Authentication.checkUserId(req.userId);
  539. JsonRoutes.sendResult(res, {
  540. code: 200,
  541. data: Boards.find({ permission: 'public' }).map(function (doc) {
  542. return {
  543. _id: doc._id,
  544. title: doc.title,
  545. };
  546. }),
  547. });
  548. }
  549. catch (error) {
  550. JsonRoutes.sendResult(res, {
  551. code: 200,
  552. data: error,
  553. });
  554. }
  555. });
  556. JsonRoutes.add('GET', '/api/boards/:id', function (req, res, next) {
  557. try {
  558. const id = req.params.id;
  559. Authentication.checkBoardAccess(req.userId, id);
  560. JsonRoutes.sendResult(res, {
  561. code: 200,
  562. data: Boards.findOne({ _id: id }),
  563. });
  564. }
  565. catch (error) {
  566. JsonRoutes.sendResult(res, {
  567. code: 200,
  568. data: error,
  569. });
  570. }
  571. });
  572. JsonRoutes.add('POST', '/api/boards', function (req, res, next) {
  573. try {
  574. Authentication.checkUserId(req.userId);
  575. const id = Boards.insert({
  576. title: req.body.title,
  577. members: [
  578. {
  579. userId: req.body.owner,
  580. isAdmin: true,
  581. isActive: true,
  582. isCommentOnly: false,
  583. },
  584. ],
  585. permission: 'public',
  586. color: 'belize',
  587. });
  588. JsonRoutes.sendResult(res, {
  589. code: 200,
  590. data: {
  591. _id: id,
  592. },
  593. });
  594. }
  595. catch (error) {
  596. JsonRoutes.sendResult(res, {
  597. code: 200,
  598. data: error,
  599. });
  600. }
  601. });
  602. JsonRoutes.add('DELETE', '/api/boards/:id', function (req, res, next) {
  603. try {
  604. Authentication.checkUserId(req.userId);
  605. const id = req.params.id;
  606. Boards.remove({ _id: id });
  607. JsonRoutes.sendResult(res, {
  608. code: 200,
  609. data:{
  610. _id: id,
  611. },
  612. });
  613. }
  614. catch (error) {
  615. JsonRoutes.sendResult(res, {
  616. code: 200,
  617. data: error,
  618. });
  619. }
  620. });
  621. }