File size: 6,351 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// @flow
const { db } = require('shared/db');
import { decrementMemberCount, setMemberCount } from './channel';
import type { DBUsersChannels } from 'shared/types';

/*
===========================================================

        MODIFYING AND CREATING DATA IN USERSCHANNELS

===========================================================
*/

// removes all the user relationships to a channel. will be invoked when a
// channel is deleted, at which point we don't want any records in the
// database to show a user relationship to the deleted channel
// prettier-ignore
const removeMembersInChannel = async (channelId: string): Promise<Array<?DBUsersChannels>> => {
  await setMemberCount(channelId, 0)

  return db
    .table('usersChannels')
    .getAll(channelId, { index: 'channelId' })
    .update({
      isMember: false,
      receiveNotifications: false,
    })
    .run();
};

// toggles all pending users to make them a member in a channel. invoked by a
// channel or community owner when turning a private channel into a public
// channel
// prettier-ignore
const approvePendingUsersInChannel = async (channelId: string): Promise<DBUsersChannels> => {
  const currentCount = await db.table('usersChannels')
    .getAll(
      [channelId, 'member'],
      [channelId, 'moderator'],
      [channelId, 'owner'],
      {
        index: 'channelIdAndRole',
      }
    )
    .count()
    .default(1)
    .run()

  const pendingCount = await db.table('usersChannels')
    .getAll([channelId, "pending"], { index: 'channelIdAndRole' })
    .count()
    .default(0)
    .run()

  setMemberCount(channelId, currentCount + pendingCount)

  return db
    .table('usersChannels')
    .getAll([channelId, "pending"], { index: 'channelIdAndRole' })
    .update(
      {
        isMember: true,
        isPending: false,
        receiveNotifications: true,
      },
      { returnChanges: true }
    )
    .run()
};

const removeUsersChannelMemberships = async (userId: string) => {
  const usersChannels = await db
    .table('usersChannels')
    .getAll(userId, { index: 'userId' })
    .run();

  if (!usersChannels || usersChannels.length === 0) return;

  const memberCountPromises = usersChannels.map(usersChannel => {
    return decrementMemberCount(usersChannel.channelId);
  });

  const channelPromise = db
    .table('usersChannels')
    .getAll(userId, { index: 'userId' })
    .update({
      isOwner: false,
      isModerator: false,
      isMember: false,
      receiveNotifications: false,
    })
    .run();

  return await Promise.all([memberCountPromises, channelPromise]);
};

/*
===========================================================

            GETTING DATA FROM USERSCHANNELS

===========================================================
*/

type Options = { first: number, after: number };
// prettier-ignore
const getMembersInChannel = (channelId: string, options: Options): Promise<Array<string>> => {
  const { first, after } = options

  return (
    db
      .table('usersChannels')
      .getAll([channelId, "member"], [channelId, "moderator"], [channelId, "owner"], { index: 'channelIdAndRole' })
      .skip(after || 0)
      .limit(first || 25)
      // return an array of the userIds to be loaded by gql
      .map(userChannel => userChannel('userId'))
      .run()
  );
};

const getModeratorsInChannel = (channelId: string): Promise<Array<string>> => {
  return (
    db
      .table('usersChannels')
      .getAll([channelId, 'moderator'], {
        index: 'channelIdAndRole',
      })
      // return an array of the userIds to be loaded by gql
      .map(userChannel => userChannel('userId'))
      .run()
  );
};

const getOwnersInChannel = (channelId: string): Promise<Array<string>> => {
  return (
    db
      .table('usersChannels')
      .getAll([channelId, 'owner'], {
        index: 'channelIdAndRole',
      })
      // return an array of the userIds to be loaded by gql
      .map(userChannel => userChannel('userId'))
      .run()
  );
};

const DEFAULT_USER_CHANNEL_PERMISSIONS = {
  isOwner: false,
  isMember: false,
  isModerator: false,
  isBlocked: false,
  isPending: false,
  receiveNotifications: false,
};

// prettier-ignore
const getUserPermissionsInChannel = (channelId: string, userId: string): Promise<DBUsersChannels> => {
  return db
    .table('usersChannels')
    .getAll([userId, channelId], { index: 'userIdAndChannelId' })
    .run()
    .then(data => {
      // if a record exists
      if (data.length > 0) {
        return data[0];
      } else {
        // if a record doesn't exist, we're creating a new relationship
        // so default to false for everything
        return DEFAULT_USER_CHANNEL_PERMISSIONS;
      }
    });
};

type UserIdAndChannelId = [?string, string];

// prettier-ignore
const getUsersPermissionsInChannels = (input: Array<UserIdAndChannelId>): Promise<Array<DBUsersChannels>> => {
  return db
    .table('usersChannels')
    .getAll(...input, { index: 'userIdAndChannelId' })
    .run()
    .then(data => {
      if (!data || data.length === 0)
        return Array.from({ length: input.length }).map((_, index) => ({
          ...DEFAULT_USER_CHANNEL_PERMISSIONS,
          userId: input[index][0],
          channelId: input[index][1],
        }));

      return data.map((rec, index) => {
        if (rec) return rec;

        return {
          ...DEFAULT_USER_CHANNEL_PERMISSIONS,
          userId: input[index][0],
          channelId: input[index][1],
        };
      });
    });
};

const getUserUsersChannels = (userId: string) => {
  return db
    .table('usersChannels')
    .getAll([userId, 'member'], [userId, 'owner'], [userId, 'moderator'], {
      index: 'userIdAndRole',
    })
    .run();
};

const getUserChannelIds = (userId: string) => {
  return db
    .table('usersChannels')
    .getAll([userId, 'member'], [userId, 'owner'], [userId, 'moderator'], {
      index: 'userIdAndRole',
    })
    .map(rec => rec('channelId'))
    .run();
};

module.exports = {
  // modify and create
  removeMembersInChannel,
  approvePendingUsersInChannel,
  removeUsersChannelMemberships,
  // get
  getMembersInChannel,
  getModeratorsInChannel,
  getOwnersInChannel,
  getUserPermissionsInChannel,
  getUsersPermissionsInChannels,
  getUserUsersChannels,
  getUserChannelIds,
  // constants
  DEFAULT_USER_CHANNEL_PERMISSIONS,
};