Gitter migration: Setup redirects (rollout pt. 3)
[gitter.git] / server / services / repo-premium-status-notifier.js
blob3556375fd1c2bd3809c2a8b165aefdc3c24093ce
1 'use strict';
3 var troupeDao = require('./daos/troupe-dao').lean;
4 var appEvents = require('gitter-web-appevents');
5 var userService = require('gitter-web-users');
6 var roomMembershipService = require('gitter-web-rooms/lib/room-membership-service');
7 var debug = require('debug')('gitter:app:repo-premium-status-notifier');
9 function repoPremiumStatusNotifier(userOrOrg, premiumStatus) {
10 return userService.findByUsername(userOrOrg).then(function(user) {
11 var isOrg = !user;
13 if (!isOrg) {
14 debug('Notifying of user premium status change: %s', userOrOrg);
15 // For a user
16 appEvents.dataChange2(
17 '/user/' + user._id,
18 'patch',
20 id: '' + user._id,
21 premium: premiumStatus
23 'user'
27 debug('Searching for all rooms owned by: %s', userOrOrg);
28 return troupeDao
29 .findByOwnerUri(userOrOrg, { _id: 1 })
30 .then(function(troupes) {
31 debug('Found %s rooms owned by %s', troupes.length, userOrOrg);
33 var troupeIds = troupes.map(function(troupe) {
34 return troupe._id;
35 });
37 debug('Search for all users in all rooms owned by %s', userOrOrg);
38 return roomMembershipService.findMembersForRoomMulti(troupeIds);
40 .then(function(troupeUsersHash) {
41 var count = 0;
42 var userNotificatons = {};
44 Object.keys(troupeUsersHash).forEach(function(troupeId) {
45 var userIds = troupeUsersHash[troupeId];
47 userIds.forEach(function(userId) {
48 count++;
49 if (isOrg) {
50 // TODO: come up with a better mapping from org to user
51 if (!userNotificatons[userId]) {
52 // Only do this once per user
53 userNotificatons[userId] = true;
55 appEvents.dataChange2(
56 '/user/' + userId + '/orgs',
57 'patch',
59 name: userOrOrg, // Id for org is the name
60 premium: premiumStatus
62 'user'
67 appEvents.dataChange2(
68 '/user/' + userId + '/rooms',
69 'patch',
71 id: '' + troupeId,
72 premium: premiumStatus
74 'room'
76 });
77 });
79 debug('Notified %s users of change of premium status', count);
80 });
81 });
84 module.exports = repoPremiumStatusNotifier;