3 var Promise = require('bluebird');
4 var TroupeUser = require('gitter-web-persistence').TroupeUser;
5 var _ = require('lodash');
7 function findUserRoomIdsWithinGroup(groupId, userId) {
8 return TroupeUser.aggregate([
9 { $match: { userId: userId } },
10 { $project: { _id: '$troupeId' } },
24 'troupe.groupId': groupId
34 .then(function(results) {
35 return _.map(results, function(f) {
41 function queryForPublicRooms(groupId) {
42 return { groupId: groupId, 'sd.public': true };
45 function queryForPublicRoomsInGroupIds(groupIds) {
46 return { groupId: { $in: groupIds }, 'sd.public': true };
49 function queryForAccessibleRooms(groupId, userId) {
50 if (!userId) return queryForPublicRooms(groupId);
52 return findUserRoomIdsWithinGroup(groupId, userId).then(function(memberTroupeIds) {
56 { _id: { $in: memberTroupeIds } },
57 { 'sd.public': true },
58 { 'sd.extraAdmins': { $elemMatch: { $eq: userId } } },
59 { 'sd.extraMembers': { $elemMatch: { $eq: userId } } }
66 queryForPublicRooms: queryForPublicRooms,
67 queryForPublicRoomsInGroupIds: queryForPublicRoomsInGroupIds,
68 queryForAccessibleRooms: Promise.method(queryForAccessibleRooms)