3 var persistence = require('gitter-web-persistence');
4 var userService = require('gitter-web-users');
5 var collections = require('gitter-web-utils/lib/collections');
6 var mongoUtils = require('gitter-web-persistence-utils/lib/mongo-utils');
7 var Promise = require('bluebird');
8 var roomMembershipService = require('./room-membership-service');
11 * Returns the URL a particular user would see if they wish to view a URL.
12 * NB: this call has to query the db to get a user's username. Don't call it
15 function getUrlForTroupeForUserId(troupe, userId) {
16 if (!troupe.oneToOne) {
17 return Promise.resolve('/' + troupe.uri);
20 var otherTroupeUser = troupe.oneToOneUsers.filter(function(troupeUser) {
21 return troupeUser.userId != userId;
25 return Promise.reject(new Error('Unable to determine other user for troupe#' + troupe.id));
27 return userService.findUsernameForUserId(otherTroupeUser.userId).then(function(username) {
28 return username ? '/' + username : '/one-one/' + otherTroupeUser.userId; // TODO: this must go
31 exports.getUrlForTroupeForUserId = getUrlForTroupeForUserId;
33 function getUrlOfFirstAccessibleRoom(troupeIds, userId) {
34 if (!troupeIds.length) return Promise.resolve(null);
36 return roomMembershipService
37 .findUserMembershipInRooms(userId, troupeIds)
38 .then(function(memberTroupeIds) {
39 return persistence.Troupe.find(
41 _id: { $in: mongoUtils.asObjectIDs(memberTroupeIds) },
42 status: { $ne: 'DELETED' }
51 .then(function(results) {
52 var resultsHash = collections.indexById(results);
53 for (var i = 0; i < troupeIds.length; i++) {
54 var troupeId = troupeIds[i];
55 var troupe = resultsHash[troupeId];
58 return getUrlForTroupeForUserId(troupe, userId);
65 exports.getUrlOfFirstAccessibleRoom = getUrlOfFirstAccessibleRoom;