boards.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. Boards = new Mongo.Collection('boards');
  2. Boards.attachSchema(new SimpleSchema({
  3. title: {
  4. type: String,
  5. },
  6. slug: {
  7. type: String,
  8. },
  9. archived: {
  10. type: Boolean,
  11. },
  12. createdAt: {
  13. type: Date,
  14. denyUpdate: true,
  15. },
  16. // XXX Inconsistent field naming
  17. modifiedAt: {
  18. type: Date,
  19. denyInsert: true,
  20. optional: true,
  21. },
  22. // De-normalized number of users that have starred this board
  23. stars: {
  24. type: Number,
  25. },
  26. // De-normalized label system
  27. 'labels.$._id': {
  28. // We don't specify that this field must be unique in the board because that
  29. // will cause performance penalties and is not necessary since this field is
  30. // always set on the server.
  31. // XXX Actually if we create a new label, the `_id` is set on the client
  32. // without being overwritten by the server, could it be a problem?
  33. type: String,
  34. },
  35. 'labels.$.name': {
  36. type: String,
  37. optional: true,
  38. },
  39. 'labels.$.color': {
  40. type: String,
  41. allowedValues: [
  42. 'green', 'yellow', 'orange', 'red', 'purple',
  43. 'blue', 'sky', 'lime', 'pink', 'black',
  44. ],
  45. },
  46. // XXX We might want to maintain more informations under the member sub-
  47. // documents like de-normalized meta-data (the date the member joined the
  48. // board, the number of contributions, etc.).
  49. 'members.$.userId': {
  50. type: String,
  51. },
  52. 'members.$.isAdmin': {
  53. type: Boolean,
  54. },
  55. 'members.$.isActive': {
  56. type: Boolean,
  57. },
  58. permission: {
  59. type: String,
  60. allowedValues: ['public', 'private'],
  61. },
  62. color: {
  63. type: String,
  64. allowedValues: [
  65. 'belize',
  66. 'nephritis',
  67. 'pomegranate',
  68. 'pumpkin',
  69. 'wisteria',
  70. 'midnight',
  71. ],
  72. },
  73. description: {
  74. type: String,
  75. optional: true,
  76. },
  77. }));
  78. Boards.helpers({
  79. /**
  80. * Is current logged-in user authorized to view this board?
  81. */
  82. isVisibleByUser() {
  83. if(this.isPublic()) {
  84. // public boards are visible to everyone
  85. return true;
  86. } else {
  87. // otherwise you have to be logged-in and active member
  88. return this.isActiveMember(Meteor.userId());
  89. }
  90. },
  91. /**
  92. * Is the user one of the active members of the board?
  93. *
  94. * @param userId
  95. * @returns {boolean} the member that matches, or undefined/false
  96. */
  97. isActiveMember(userId) {
  98. if(userId) {
  99. return this.members.find((member) => (member.userId === userId && member.isActive));
  100. } else {
  101. return false;
  102. }
  103. },
  104. isPublic() {
  105. return this.permission === 'public';
  106. },
  107. lists() {
  108. return Lists.find({ boardId: this._id, archived: false }, { sort: { sort: 1 }});
  109. },
  110. activities() {
  111. return Activities.find({ boardId: this._id }, { sort: { createdAt: -1 }});
  112. },
  113. activeMembers() {
  114. return _.where(this.members, {isActive: true});
  115. },
  116. activeAdmins() {
  117. return _.where(this.members, {isActive: true, isAdmin: true});
  118. },
  119. memberUsers() {
  120. return Users.find({ _id: {$in: _.pluck(this.members, 'userId')} });
  121. },
  122. getLabel(name, color) {
  123. return _.findWhere(this.labels, { name, color });
  124. },
  125. labelIndex(labelId) {
  126. return _.pluck(this.labels, '_id').indexOf(labelId);
  127. },
  128. memberIndex(memberId) {
  129. return _.pluck(this.members, 'userId').indexOf(memberId);
  130. },
  131. absoluteUrl() {
  132. return FlowRouter.path('board', { id: this._id, slug: this.slug });
  133. },
  134. colorClass() {
  135. return `board-color-${this.color}`;
  136. },
  137. // XXX currently mutations return no value so we have an issue when using addLabel in import
  138. // XXX waiting on https://github.com/mquandalle/meteor-collection-mutations/issues/1 to remove...
  139. pushLabel(name, color) {
  140. const _id = Random.id(6);
  141. Boards.direct.update(this._id, { $push: {labels: { _id, name, color }}});
  142. return _id;
  143. },
  144. });
  145. Boards.mutations({
  146. archive() {
  147. return { $set: { archived: true }};
  148. },
  149. restore() {
  150. return { $set: { archived: false }};
  151. },
  152. rename(title) {
  153. return { $set: { title }};
  154. },
  155. setDesciption(description) {
  156. return { $set: {description} };
  157. },
  158. setColor(color) {
  159. return { $set: { color }};
  160. },
  161. setVisibility(visibility) {
  162. return { $set: { permission: visibility }};
  163. },
  164. addLabel(name, color) {
  165. // If label with the same name and color already exists we don't want to
  166. // create another one because they would be indistinguishable in the UI
  167. // (they would still have different `_id` but that is not exposed to the
  168. // user).
  169. if (!this.getLabel(name, color)) {
  170. const _id = Random.id(6);
  171. return { $push: {labels: { _id, name, color }}};
  172. }
  173. },
  174. editLabel(labelId, name, color) {
  175. if (!this.getLabel(name, color)) {
  176. const labelIndex = this.labelIndex(labelId);
  177. return {
  178. $set: {
  179. [`labels.${labelIndex}.name`]: name,
  180. [`labels.${labelIndex}.color`]: color,
  181. },
  182. };
  183. }
  184. },
  185. removeLabel(labelId) {
  186. return { $pull: { labels: { _id: labelId }}};
  187. },
  188. addMember(memberId) {
  189. const memberIndex = this.memberIndex(memberId);
  190. if (memberIndex === -1) {
  191. const xIndex = this.memberIndex('x');
  192. if (xIndex === -1) {
  193. return {
  194. $push: {
  195. members: {
  196. userId: memberId,
  197. isAdmin: false,
  198. isActive: true,
  199. },
  200. },
  201. };
  202. } else {
  203. return {
  204. $set: {
  205. [`members.${xIndex}.userId`]: memberId,
  206. [`members.${xIndex}.isActive`]: true,
  207. [`members.${xIndex}.isAdmin`]: false,
  208. },
  209. };
  210. }
  211. } else {
  212. return {
  213. $set: {
  214. [`members.${memberIndex}.isActive`]: true,
  215. },
  216. };
  217. }
  218. },
  219. removeMember(memberId) {
  220. const memberIndex = this.memberIndex(memberId);
  221. // we do not allow the only one admin to be removed
  222. const allowRemove = (!this.members[memberIndex].isAdmin) || (this.activeAdmins().length > 1);
  223. if (allowRemove) {
  224. return {
  225. $set: {
  226. [`members.${memberIndex}.userId`]: 'x',
  227. [`members.${memberIndex}.isActive`]: false,
  228. [`members.${memberIndex}.isAdmin`]: false,
  229. },
  230. };
  231. } else {
  232. return {
  233. $set: {
  234. [`members.${memberIndex}.isActive`]: true,
  235. },
  236. };
  237. }
  238. },
  239. setMemberPermission(memberId, isAdmin) {
  240. const memberIndex = this.memberIndex(memberId);
  241. // do not allow change permission of self
  242. if (memberId === Meteor.userId()) {
  243. isAdmin = this.members[memberIndex].isAdmin;
  244. }
  245. return {
  246. $set: {
  247. [`members.${memberIndex}.isAdmin`]: isAdmin,
  248. },
  249. };
  250. },
  251. });
  252. if (Meteor.isServer) {
  253. Boards.allow({
  254. insert: Meteor.userId,
  255. update: allowIsBoardAdmin,
  256. remove: allowIsBoardAdmin,
  257. fetch: ['members'],
  258. });
  259. // The number of users that have starred this board is managed by trusted code
  260. // and the user is not allowed to update it
  261. Boards.deny({
  262. update(userId, board, fieldNames) {
  263. return _.contains(fieldNames, 'stars');
  264. },
  265. fetch: [],
  266. });
  267. // We can't remove a member if it is the last administrator
  268. Boards.deny({
  269. update(userId, doc, fieldNames, modifier) {
  270. if (!_.contains(fieldNames, 'members'))
  271. return false;
  272. // We only care in case of a $pull operation, ie remove a member
  273. if (!_.isObject(modifier.$pull && modifier.$pull.members))
  274. return false;
  275. // If there is more than one admin, it's ok to remove anyone
  276. const nbAdmins = _.where(doc.members, {isActive: true, isAdmin: true}).length;
  277. if (nbAdmins > 1)
  278. return false;
  279. // If all the previous conditions were verified, we can't remove
  280. // a user if it's an admin
  281. const removedMemberId = modifier.$pull.members.userId;
  282. return Boolean(_.findWhere(doc.members, {
  283. userId: removedMemberId,
  284. isAdmin: true,
  285. }));
  286. },
  287. fetch: ['members'],
  288. });
  289. Meteor.methods({
  290. quitBoard(boardId) {
  291. check(boardId, String);
  292. const board = Boards.findOne(boardId);
  293. if (board) {
  294. const userId = Meteor.userId();
  295. const index = board.memberIndex(userId);
  296. if (index>=0) {
  297. board.removeMember(userId);
  298. return true;
  299. } else throw new Meteor.Error('error-board-notAMember');
  300. } else throw new Meteor.Error('error-board-doesNotExist');
  301. },
  302. });
  303. }
  304. Boards.before.insert((userId, doc) => {
  305. // XXX We need to improve slug management. Only the id should be necessary
  306. // to identify a board in the code.
  307. // XXX If the board title is updated, the slug should also be updated.
  308. // In some cases (Chinese and Japanese for instance) the `getSlug` function
  309. // return an empty string. This is causes bugs in our application so we set
  310. // a default slug in this case.
  311. doc.slug = doc.slug || getSlug(doc.title) || 'board';
  312. doc.createdAt = new Date();
  313. doc.archived = false;
  314. doc.members = doc.members || [{
  315. userId,
  316. isAdmin: true,
  317. isActive: true,
  318. }];
  319. doc.stars = 0;
  320. doc.color = Boards.simpleSchema()._schema.color.allowedValues[0];
  321. // Handle labels
  322. const colors = Boards.simpleSchema()._schema['labels.$.color'].allowedValues;
  323. const defaultLabelsColors = _.clone(colors).splice(0, 6);
  324. doc.labels = defaultLabelsColors.map((color) => {
  325. return {
  326. color,
  327. _id: Random.id(6),
  328. name: '',
  329. };
  330. });
  331. });
  332. Boards.before.update((userId, doc, fieldNames, modifier) => {
  333. modifier.$set = modifier.$set || {};
  334. modifier.$set.modifiedAt = new Date();
  335. });
  336. if (Meteor.isServer) {
  337. // Let MongoDB ensure that a member is not included twice in the same board
  338. Meteor.startup(() => {
  339. Boards._collection._ensureIndex({
  340. _id: 1,
  341. 'members.userId': 1,
  342. }, { unique: true });
  343. });
  344. // Genesis: the first activity of the newly created board
  345. Boards.after.insert((userId, doc) => {
  346. Activities.insert({
  347. userId,
  348. type: 'board',
  349. activityTypeId: doc._id,
  350. activityType: 'createBoard',
  351. boardId: doc._id,
  352. });
  353. });
  354. // If the user remove one label from a board, we cant to remove reference of
  355. // this label in any card of this board.
  356. Boards.after.update((userId, doc, fieldNames, modifier) => {
  357. if (!_.contains(fieldNames, 'labels') ||
  358. !modifier.$pull ||
  359. !modifier.$pull.labels ||
  360. !modifier.$pull.labels._id)
  361. return;
  362. const removedLabelId = modifier.$pull.labels._id;
  363. Cards.update(
  364. { boardId: doc._id },
  365. {
  366. $pull: {
  367. labelIds: removedLabelId,
  368. },
  369. },
  370. { multi: true }
  371. );
  372. });
  373. // Add a new activity if we add or remove a member to the board
  374. Boards.after.update((userId, doc, fieldNames, modifier) => {
  375. if (!_.contains(fieldNames, 'members'))
  376. return;
  377. let memberId;
  378. // Say hello to the new member
  379. if (modifier.$push && modifier.$push.members) {
  380. memberId = modifier.$push.members.userId;
  381. Activities.insert({
  382. userId,
  383. memberId,
  384. type: 'member',
  385. activityType: 'addBoardMember',
  386. boardId: doc._id,
  387. });
  388. }
  389. // Say goodbye to the former member
  390. if (modifier.$pull && modifier.$pull.members) {
  391. memberId = modifier.$pull.members.userId;
  392. Activities.insert({
  393. userId,
  394. memberId,
  395. type: 'member',
  396. activityType: 'removeBoardMember',
  397. boardId: doc._id,
  398. });
  399. }
  400. });
  401. }