-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDb.ts
475 lines (399 loc) · 14.5 KB
/
Db.ts
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import { deflate, inflate, JsonObject, Serializable, Serialize } from 'serialazy';
import { SerializeDate, SerializeArray, SerializeRaw } from './Serialize';
import { v4 as uuid } from 'uuid';
import * as MongoDb from 'mongodb';
import { Constructor } from 'serialazy/lib/dist/types';
import * as API from './api';
import Cfg from './Cfg';
import { Filter } from 'mongodb';
export enum BotTarget {
discord = 'discord',
slack = 'slack',
}
export function BotTargetFromString(value: string): BotTarget | undefined {
switch (value) {
case BotTarget.slack:
return BotTarget.slack;
case BotTarget.discord:
return BotTarget.discord;
}
}
export enum PersonFrameRole {
author = 'author',
artist = 'artist',
}
export class ChannelModel {
@Serialize() public id: string = '';
@Serialize() public name: string = '';
@Serialize() public target: BotTarget = BotTarget.discord;
static create(id: string, name: string, target: BotTarget) {
const model = new ChannelModel();
model.id = id;
model.name = name;
model.target = target;
return model;
}
equals(channel: ChannelModel): boolean {
return this.id === channel.id && this.target === channel.target;
}
}
export class AvatarModel {
@Serialize() public url: string = '';
@Serialize() public width: number = 0;
@Serialize() public height: number = 0;
@Serialize() public hash: string = '';
@SerializeDate() public lastUpdated: Date = new Date();
static create(url: string, width: number, height: number, hash: string): AvatarModel {
const model = new AvatarModel();
model.url = url;
model.width = width;
model.height = height;
model.hash = hash;
return model;
}
toApi(): API.Avatar {
return {
url: this.url,
width: this.width,
height: this.height,
};
}
}
export class PersonModel {
@Serialize({ name: '_id' }) public id: string = '';
@Serialize() public name: string = '';
@Serialize() public serviceId: string = '';
@Serialize() public target: BotTarget = BotTarget.discord;
@Serialize({ optional: true }) public avatar?: AvatarModel;
@Serialize({ optional: true }) public preferredPersonId?: string;
@Serialize({ optional: true }) public preferredGameRole?: PersonFrameRole;
static create(serviceId: string, name: string, target: BotTarget) {
const model = new PersonModel();
model.id = uuid();
model.serviceId = serviceId;
model.name = name;
model.target = target;
return model;
}
toApi(): API.Person {
return {
name: this.name,
avatar: this.avatar?.toApi(),
};
}
}
export class FrameImageModel {
@Serialize() public imageUrl: string = '';
@Serialize() public imageFileName: string = '';
@Serialize() public width: number = 0;
@Serialize() public height: number = 0;
static create(imageUrl: string, imageFileName: string, width: number, height: number): FrameImageModel {
const model = new FrameImageModel();
model.imageUrl = imageUrl;
model.imageFileName = imageFileName;
model.width = width;
model.height = height;
return model;
}
toApi(): API.FrameImageData {
return {
imageUrl: this.imageUrl,
width: this.width,
height: this.height,
};
}
}
export class FrameModel {
@Serialize() public id: string = '';
@Serialize() public personId: string = '';
@Serialize({ optional: true }) public title?: string;
@Serialize({ optional: true }) public image?: FrameImageModel;
@Serialize({ optional: true }) public warnings?: number;
static create(personId: string) {
const model = new FrameModel();
model.id = uuid();
model.personId = personId;
return model;
}
get isComplete(): boolean {
return !!this.title || !!this.image;
}
toApi(): API.Frame {
return {
person: { name: '' }, // Person has to be attached from the Person collection
playData: {
title: this.title,
image: this.image?.toApi(),
},
};
}
}
export class GameModel {
@Serialize({ name: '_id' }) public name: string = '';
@Serialize() public isComplete: boolean = false;
@Serialize() public channel: ChannelModel = new ChannelModel();
@SerializeArray(FrameModel) public frames: FrameModel[] = [];
@Serialize({ optional: true }) public titleImage?: FrameImageModel;
static create(name: string, channel: ChannelModel, frames: FrameModel[]) {
const model = new GameModel();
model.name = name;
model.channel = channel;
model.frames = frames;
return model;
}
toApi(): API.Game {
return {
name: this.name,
titleImage: this.titleImage?.toApi(),
frames: this.frames.map((frame) => frame.toApi()),
};
}
}
export class SlackToken {
@Serialize({ name: '_id' }) public teamId: string = '';
@Serialize({ optional: true }) public token?: string;
@SerializeRaw({ optional: true }) public installation?: any;
}
export class InterestModel {
@Serialize() public personId: string = '';
@Serialize() public channel: ChannelModel = new ChannelModel();
static create(personId: string, channelId: string, target: BotTarget) {
const model = new InterestModel();
model.personId = personId;
model.channel.id = channelId;
model.channel.target = target;
return model;
}
}
class ChannelLinkModel {
@Serialize() public lhs: ChannelModel = new ChannelModel();
@Serialize() public rhs: ChannelModel = new ChannelModel();
}
export interface GameQuery {
isComplete?: boolean;
channel?: ChannelModel;
sampleSize?: number;
limit?: number;
}
export interface IDb {
getGames(query?: GameQuery): Promise<Array<GameModel>>;
getGame(gameName: string): Promise<GameModel | undefined>;
putGame(game: GameModel): Promise<void>;
getPerson(id: string): Promise<PersonModel | undefined>;
getPersonFromService(serviceId: string, target: BotTarget): Promise<PersonModel | undefined>;
putPerson(person: PersonModel): Promise<void>;
getSlackToken(teamId: string): Promise<string | undefined>;
getSlackInstallation(teamId: string): Promise<any>;
putSlackInstallation(teamId: string, installation: any): Promise<void>;
getInterest(channel: ChannelModel): Promise<PersonModel[]>;
putInterest(person: PersonModel, channel: ChannelModel, isInterested: boolean): Promise<void>;
}
export class Db implements IDb {
client: MongoDb.MongoClient;
game: MongoDb.Collection;
person: MongoDb.Collection;
slackToken: MongoDb.Collection;
interest: MongoDb.Collection;
channelLink: MongoDb.Collection;
static async create(): Promise<Db> {
const connectionString = process.env['DB_CONNECTION_STRING'];
if (!connectionString) {
throw new Error('DB_CONNECTION_STRING is undefined');
}
const client = new MongoDb.MongoClient(connectionString);
await client.connect();
let db = new Db(client);
await db.init();
return db;
}
private constructor(client: MongoDb.MongoClient) {
this.client = client;
const db = this.client.db(Cfg.dbName);
this.game = db.collection('Game');
this.person = db.collection('Person');
this.slackToken = db.collection('SlackToken');
this.interest = db.collection('Interest');
this.channelLink = db.collection('ChannelLink');
}
private async init() {
await this.person.createIndex(
{
serviceId: 1,
target: 1,
}
// {
// unique: true,
// }
);
await this.interest.createIndex(
{
personId: 1,
'channel.id': 1,
'channel.target': 1,
},
{
unique: true,
}
);
await this.interest.createIndex({
'channel.id': 1,
'channel.target': 1,
});
}
async deinit() {
await this.client.close();
}
async getGames(query?: GameQuery): Promise<GameModel[]> {
const mongoQuery: MongoDb.Filter<any> = {};
if (query?.isComplete !== undefined && query?.isComplete !== null) {
mongoQuery.isComplete = query?.isComplete;
}
let docs: any[];
// Channel query -- this is separated because we have to first resolve linked channels
if (query?.channel) {
const channels = await this.resolveLinkedChannels(query.channel);
mongoQuery.$or = channels.map((channel) => ({
'channel.id': channel.id,
'channel.target': channel.target,
}));
}
// Sample query
if (query?.sampleSize) {
docs = await this.game
.aggregate([{ $match: mongoQuery }, { $sample: { size: query.sampleSize } }])
.toArray();
}
// Plain query
else {
docs = await this.game
.find(mongoQuery)
.sort({ name: 1 })
.limit(Math.min(query?.limit || 50, 50))
.toArray();
}
let models = this.inflateArray(docs, GameModel);
return models;
}
async getGame(gameName: string): Promise<GameModel | undefined> {
let doc = await this.game.findOne({ _id: gameName });
if (!doc) {
return undefined;
}
return inflate(GameModel, doc);
}
private deflateDoc<T>(obj: T): JsonObject {
const doc = deflate(obj);
if (typeof doc !== 'object' || Array.isArray(doc) || !doc) {
throw new Error("Deflated object can't be saved in Mongo");
}
return doc;
}
async putGame(game: GameModel): Promise<void> {
let doc = this.deflateDoc(game);
await this.game.replaceOne({ _id: game.name }, doc, { upsert: true });
// return inflate(GameModel, doc);
}
async getPerson(id: string): Promise<PersonModel | undefined> {
const doc = await this.person.findOne({ _id: id });
if (doc) {
return inflate(PersonModel, doc);
}
return undefined;
}
async getPersonFromService(serviceId: string, target: BotTarget): Promise<PersonModel | undefined> {
const doc = await this.person.findOne({ serviceId, target });
if (doc) {
return inflate(PersonModel, doc);
}
return undefined;
}
async putPerson(person: PersonModel): Promise<void> {
const doc = this.deflateDoc(person);
await this.person.replaceOne({ _id: person.id }, doc, { upsert: true });
}
private inflateArray<Type>(docs: any[], type: Constructor<Type>): Type[] {
let toReturn: Type[] = [];
docs.forEach((doc) => {
try {
toReturn.push(inflate(type, doc));
} catch (err) {}
});
return toReturn;
}
private deflateArray<Type>(objs: Type[]): any[] {
return objs.map((obj) => deflate(obj));
}
async getSlackToken(teamId: string): Promise<string | undefined> {
const doc = await this.slackToken.findOne({ _id: teamId });
if (!doc) {
return;
}
const slackToken = inflate(SlackToken, doc);
return slackToken.token || slackToken.installation?.bot?.token;
}
async getSlackInstallation(teamId: string): Promise<any> {
const doc = await this.slackToken.findOne({ _id: teamId });
if (!doc) {
return;
}
const slackToken = inflate(SlackToken, doc);
return slackToken.installation;
}
async putSlackInstallation(teamId: string, installation: any): Promise<void> {
const slackToken = new SlackToken();
slackToken.teamId = teamId;
slackToken.installation = installation;
await this.slackToken.replaceOne({ _id: teamId }, this.deflateDoc(slackToken), { upsert: true });
}
private async resolveLinkedChannels(channel: ChannelModel): Promise<ChannelModel[]> {
// Find channel links
const channelLinkDocs = await this.channelLink
.find({
$or: [
{ 'lhs.id': channel.id, 'lhs.target': channel.target },
{ 'rhs.id': channel.id, 'rhs.target': channel.target },
],
})
.toArray();
const channelLinks = this.inflateArray(channelLinkDocs, ChannelLinkModel);
const allChannels = [channel];
channelLinks.forEach((link) => {
if (!allChannels.find((channel) => link.lhs.equals(channel))) {
allChannels.push(link.lhs);
}
if (!allChannels.find((channel) => link.rhs.equals(channel))) {
allChannels.push(link.rhs);
}
});
return allChannels;
}
async getInterest(channel: ChannelModel): Promise<PersonModel[]> {
const allChannels = await this.resolveLinkedChannels(channel);
const promises = allChannels.map((theChannel) => {
return this.interest.find({ 'channel.id': theChannel.id, 'channel.target': theChannel.target }).toArray();
});
const interestDocs = (await Promise.all(promises)).flatMap((doc) => doc);
const interests = this.inflateArray(interestDocs, InterestModel);
const interestIds = interests.map((interest) => interest.personId);
if (interestIds.length === 0) {
return [];
}
// Find all people associated with these interests
const personDocs = await this.person.find({ _id: { $in: interestIds } }).toArray();
return this.inflateArray(personDocs, PersonModel);
}
async putInterest(person: PersonModel, channel: ChannelModel, isInterested: boolean): Promise<void> {
const filter = {
personId: person.id,
'channel.id': channel.id,
'channel.target': channel.target,
};
if (!isInterested) {
await this.interest.deleteMany(filter);
return;
}
const interest = InterestModel.create(person.id, channel.id, channel.target);
const doc = this.deflateDoc(interest);
await this.interest.replaceOne(filter, doc, { upsert: true });
}
}