-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.ts
More file actions
261 lines (247 loc) · 7.01 KB
/
create.ts
File metadata and controls
261 lines (247 loc) · 7.01 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import { PrismaClient } from '@prisma/client';
import {
getRateCommitmentHash,
MessageI,
randomBigInt
} from 'discreetly-interfaces';
import { genClaimCodeArray, genMockUsers } from '../../utils';
import type { Server as SocketIOServer } from 'socket.io';
import { EthGroupI } from '../../types';
const prisma = new PrismaClient();
/**
* Creates a new room with the given name and optional parameters.
* @param {string} name - The name of the room.
* @param {number} [rateLimit=10000] - The length of an epoch in milliseconds
* @param {number} [userMessageLimit=12] - The message limit per user per epoch
* @param {number} [numClaimCodes=0] - The number of claim codes to generate for the room.
* @param {number} [approxNumMockUsers=5] - The approximate number of mock users to generate for the room.
* @param {string} [type='IDENTITY_LIST'] - The type of room to create.
* @param {string[]} [adminIdentities=[]] - The identities of the admins of the room.
* @param {string} [bandadaAddress] - The address of the bandada server.
* @param {string} [bandadaGroupId] - The id of the bandada group.
* @param {string} [bandadaAPIKey] - The API key for the bandada server.
* @param {string} [membershipType] - The membership type of the room.
* @param {string} [roomId] - The ID of the room to create.
* @returns {Promise<boolean>} - A promise that resolves to true if the room was created successfully.
*/
export async function createRoom(
roomName: string,
rateLimit = 100000,
userMessageLimit = 12,
numClaimCodes = 0,
approxNumMockUsers = 5,
type: string,
adminIdentities?: string[],
bandadaAddress?: string,
bandadaGroupId?: string,
bandadaAPIKey?: string,
membershipType?: string,
roomId?: string
): Promise<
{ roomId: string; claimCodes: { claimcode: string }[] } | undefined | null
> {
const claimCodes: { claimcode: string }[] = genClaimCodeArray(numClaimCodes);
const mockUsers: string[] = genMockUsers(approxNumMockUsers);
const identityCommitments: string[] = mockUsers.map((user) =>
getRateCommitmentHash(BigInt(user), BigInt(userMessageLimit)).toString()
);
const _roomId = roomId ? roomId : randomBigInt().toString();
const room = await prisma.rooms.findUnique({ where: { roomId: _roomId } });
if (room) return null;
const roomData = {
where: {
roomId: _roomId
},
update: {},
create: {
roomId: _roomId,
name: roomName,
banRateLimit: rateLimit,
userMessageLimit: userMessageLimit,
adminIdentities: adminIdentities,
identities: identityCommitments,
bandadaAddress,
bandadaGroupId,
bandadaAPIKey,
type,
membershipType,
claimCodes: {
create: claimCodes
},
gateways: {
create: mockUsers.map((user) => ({
semaphoreIdentity: user
}))
}
}
};
return await prisma.rooms
.upsert(roomData)
.then(() => {
return { roomId: _roomId, claimCodes };
})
.catch((err) => {
console.error(err);
return undefined;
});
}
/**
* This function creates a system message in a room.
* The message will be the same in all rooms if no roomId is passed.
* If a roomId is passed, the message will be created in that room.
* @param {string} message - The message to be created
* @param {string} roomId - The roomId to create the message in
*/
export function createSystemMessages(
message: string,
roomId?: string,
io?: SocketIOServer
): Promise<unknown> {
const query = roomId ? { where: { roomId } } : undefined;
return prisma.rooms
.findMany(query)
.then((rooms) => {
if (roomId && rooms.length === 0) {
return Promise.reject('Room not found');
}
const createMessagePromises = rooms.map((room) => {
const createMessage = prisma.messages.create({
data: {
message,
roomId: room.roomId,
messageId: '0',
proof: JSON.stringify({})
}
});
if (io) {
io.to(room.roomId).emit('systemMessage', createMessage);
}
return createMessage;
});
return Promise.all(createMessagePromises);
})
.catch((err) => {
console.error(err);
return Promise.reject(err);
});
}
/**
* Adds a message to a room.
* @param {string} roomId - The ID of the room to add the message to.
* @param {MessageI} message - The message to add to the room.
* @returns {Promise<unknown>} - A promise that resolves when the message has been added to the room.
*/
export function createMessageInRoom(
roomId: string,
message: MessageI
): Promise<unknown> {
if (!message.epoch) {
throw new Error('Epoch not provided');
}
return prisma.rooms.update({
where: {
roomId: roomId
},
data: {
epochs: {
create: {
epoch: String(message.epoch),
messages: {
create: {
message: message.message ? String(message.message) : '',
messageId: message.messageId ? message.messageId.toString() : '',
messageType: message.messageType,
proof: JSON.stringify(message.proof),
roomId: roomId
}
}
}
}
}
});
}
export function createEthGroup(
name: string,
roomIds: string[]
): Promise<EthGroupI> {
return prisma.ethereumGroup.create({
data: {
name: name,
rooms: {
connect: roomIds.map((roomId) => ({ roomId }))
}
}
});
}
export function createClaimCode(
claimCode: string,
roomIds: string[],
expiresAt: number,
usesLeft: number,
discordId: string,
roomId?: string
) {
if (!roomId) {
return prisma.claimCodes.create({
data: {
claimcode: claimCode,
roomIds: roomIds,
expiresAt: expiresAt,
usesLeft: usesLeft,
discordId: discordId
}
});
} else {
return prisma.claimCodes.create({
data: {
claimcode: claimCode,
roomIds: roomIds,
expiresAt: expiresAt,
usesLeft: usesLeft,
discordId: discordId,
rooms: {
connect: {
roomId: roomId
}
}
}
});
}
}
export async function joinRoomsFromEthAddress(
recoveredAddress: string,
message: string
) {
const gatewayIdentity = await prisma.gateWayIdentity.upsert({
where: { semaphoreIdentity: message },
update: {},
create: {
semaphoreIdentity: message
}
});
await prisma.ethereumAddress.upsert({
where: { ethereumAddress: recoveredAddress },
update: {},
create: {
ethereumAddress: recoveredAddress,
gatewayId: gatewayIdentity.id
}
});
const roomsToJoin = await prisma.ethereumGroup.findMany({
where: {
ethereumAddresses: {
has: recoveredAddress
}
},
select: {
roomIds: true
}
});
const roomIdsSet = new Set(roomsToJoin.map((room) => room.roomIds).flat());
const roomIds = Array.from(roomIdsSet);
await prisma.gateWayIdentity.update({
where: { id: gatewayIdentity.id },
data: { roomIds: { set: roomIds } }
});
return roomIds;
}