universo-platform-3d

Форк
0
405 строк · 10.8 Кб
1
import {
2
  MessageBody,
3
  SubscribeMessage,
4
  WebSocketGateway
5
} from '@nestjs/websockets'
6
import { SpaceObjectService } from './space-object.service'
7
import { Logger, UseFilters, UseGuards, UseInterceptors } from '@nestjs/common'
8
import { CreateSpaceObjectDto } from './dto/create-space-object.dto'
9
import { UpdateSpaceObjectDto } from './dto/update-space-object.dto'
10
import { UpdateBatchSpaceObjectDto } from './dto/update-batch-space-object.dto'
11
import { GodotSocketInterceptor } from '../godot-server/godot-socket.interceptor'
12
import { GodotSocketExceptionFilter } from '../godot-server/godot-socket-exception.filter'
13
import { SpaceObjectId, UserId } from '../util/mongo-object-id-helpers'
14
import {
15
  AdminTokenWS,
16
  UserTokenWS
17
} from '../godot-server/get-user-ws.decorator'
18
import { da } from 'date-fns/locale'
19
import { WsAuthGuard } from '../godot-server/ws-auth.guard'
20

21
enum ZoneSpaceObjectWsMessage {
22
  GET = 'zone_get_space_object',
23
  CREATE = 'zone_create_space_object',
24
  UPDATE = 'zone_update_space_object',
25
  REMOVE = 'zone_delete_space_object',
26
  GET_PAGE = 'zone_get_space_objects_page',
27
  GET_BATCH = 'zone_get_batch_space_objects',
28
  GET_PRELOAD_SPACE_OBJECTS = 'zone_get_preload_space_objects',
29
  UPDATE_BATCH = 'zone_update_batch_space_objects',
30
  REMOVE_BATCH = 'zone_delete_batch_space_objects'
31
}
32

33
@WebSocketGateway()
34
@UseGuards(WsAuthGuard)
35
@UseInterceptors(GodotSocketInterceptor)
36
@UseFilters(GodotSocketExceptionFilter)
37
export class SpaceObjectGateway {
38
  constructor(
39
    private readonly spaceObjectService: SpaceObjectService,
40
    private readonly logger: Logger
41
  ) {}
42

43
  @SubscribeMessage(ZoneSpaceObjectWsMessage.CREATE)
44
  public create(
45
    @AdminTokenWS() isAdmin: boolean,
46
    @UserTokenWS('user_id') userId: UserId,
47
    @MessageBody('dto')
48
    createSpaceObjectDto: CreateSpaceObjectDto & { creatorUserId?: UserId }
49
  ) {
50
    this.logger.log(
51
      `${JSON.stringify(
52
        {
53
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.CREATE,
54
          createSpaceObjectDto: createSpaceObjectDto
55
          // TODO: this needs to be updated to include the creator's user ID! 2023-04-21 01:01:06. Do not merge until the Godot server adds that in.
56
        },
57
        null,
58
        2
59
      )}`,
60
      SpaceObjectGateway.name
61
    )
62

63
    if (userId) {
64
      return this.spaceObjectService.createOneWithRolesCheck(
65
        userId,
66
        createSpaceObjectDto
67
      )
68
    }
69

70
    if (isAdmin) {
71
      return this.spaceObjectService.createOneAdmin(createSpaceObjectDto)
72
    }
73
    return
74
  }
75

76
  @SubscribeMessage(ZoneSpaceObjectWsMessage.GET_PAGE)
77
  public getAllBySpaceIdPaginated(
78
    @AdminTokenWS() isAdmin: boolean,
79
    @UserTokenWS('user_id') userId: UserId,
80
    @MessageBody('id') spaceId: string,
81
    @MessageBody('page') page: number,
82
    @MessageBody('perPage') perPage: number
83
  ) {
84
    this.logger.log(
85
      `${JSON.stringify(
86
        {
87
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.GET_PAGE,
88
          spaceId,
89
          page,
90
          perPage
91
        },
92
        null,
93
        2
94
      )}`,
95
      SpaceObjectGateway.name
96
    )
97

98
    if (isAdmin) {
99
      return this.spaceObjectService.getAllBySpaceIdPaginatedAdmin(spaceId, {
100
        page,
101
        perPage
102
      })
103
    }
104

105
    if (userId) {
106
      return this.spaceObjectService.getAllBySpaceIdPaginatedWithRolesCheck(
107
        userId,
108
        spaceId,
109
        {
110
          page,
111
          perPage
112
        }
113
      )
114
    }
115
    return
116
  }
117

118
  @SubscribeMessage(ZoneSpaceObjectWsMessage.GET_BATCH)
119
  public findMany(
120
    @AdminTokenWS() isAdmin: boolean,
121
    @UserTokenWS('user_id') userId: UserId,
122
    @MessageBody('batch') ids: string[],
123
    @MessageBody('page') page: number,
124
    @MessageBody('perPage') perPage: number
125
  ) {
126
    this.logger.log(
127
      `${JSON.stringify(
128
        {
129
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.GET_BATCH,
130
          'batch (ids)': ids,
131
          page,
132
          perPage
133
        },
134
        null,
135
        2
136
      )}`,
137
      SpaceObjectGateway.name
138
    )
139
    if (isAdmin) {
140
      return this.spaceObjectService.findManyAdmin(ids, { page, perPage })
141
    }
142

143
    if (userId) {
144
      return this.spaceObjectService.findManyWithRolesCheck(userId, ids, {
145
        page,
146
        perPage
147
      })
148
    }
149
    return
150
  }
151

152
  @SubscribeMessage(ZoneSpaceObjectWsMessage.GET_PRELOAD_SPACE_OBJECTS)
153
  public getAllPreloadSpaceObjectsBySpaceIdPaginated(
154
    @AdminTokenWS() isAdmin: boolean,
155
    @UserTokenWS('user_id') userId: UserId,
156
    @MessageBody('id') spaceId: string,
157
    @MessageBody('page') page: number,
158
    @MessageBody('perPage') perPage: number
159
  ) {
160
    const options = { space: spaceId, preloadBeforeSpaceStarts: true }
161
    this.logger.log(
162
      `${JSON.stringify(
163
        {
164
          ZoneSpaceObjectWsMessage:
165
            ZoneSpaceObjectWsMessage.GET_PRELOAD_SPACE_OBJECTS,
166
          spaceId,
167
          page,
168
          perPage,
169
          options
170
        },
171
        null,
172
        2
173
      )}`,
174
      SpaceObjectGateway.name
175
    )
176

177
    if (isAdmin) {
178
      return this.spaceObjectService.getAllBySpaceIdPaginatedAdmin(
179
        spaceId,
180
        {
181
          page,
182
          perPage
183
        },
184
        options
185
      )
186
    }
187

188
    if (userId) {
189
      return this.spaceObjectService.getAllBySpaceIdPaginatedWithRolesCheck(
190
        userId,
191
        spaceId,
192
        {
193
          page,
194
          perPage
195
        },
196
        options
197
      )
198
    }
199
    return
200
  }
201

202
  /**
203
   * @description Returns the spaceObject with optional populated properties
204
   * populateParent: true: populates the single parentSpaceObject property to be the object
205
   * recursiveParentLookup: true: will recursively populate the parentSpaceObject property AND the parentSpaceObject (so populateParent is disregarded)
206
   * recursiveChildrenPopulate: true: will recursively populate childSpaceObjects
207
   *
208
   * Walkthrough: https://www.loom.com/share/a4e5e27f27b849fabdb1806235c7e48b
209
   * @date 2023-07-04 17:43
210
   */
211
  @SubscribeMessage(ZoneSpaceObjectWsMessage.GET)
212
  public async findOneWithSingleParentSpaceObject(
213
    @AdminTokenWS() isAdmin: boolean,
214
    @UserTokenWS('user_id') userId: UserId,
215
    @MessageBody('id') spaceObjectId: SpaceObjectId,
216
    @MessageBody('populateParent') populateParent = false, // if true, decently fast, 1 lookup
217
    @MessageBody('recursiveParentPopulate') recursiveParentPopulate = false, // if true, slower with $graphLookup
218
    @MessageBody('recursiveChildrenPopulate') recursiveChildrenPopulate = false // if true, slowest because 2 $graphLookups
219
  ) {
220
    if (!isAdmin && !userId) {
221
      return
222
    }
223
    this.logger.log(
224
      `${JSON.stringify(
225
        {
226
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.GET,
227
          id: spaceObjectId,
228
          populateParent,
229
          recursiveParentPopulate,
230
          recursiveChildrenPopulate
231
        },
232
        null,
233
        2
234
      )}`,
235
      SpaceObjectGateway.name
236
    )
237
    let returnData: any
238
    // first check the parent populates, prioritizing recursiveParentPopulate
239
    if (recursiveParentPopulate) {
240
      returnData =
241
        await this.spaceObjectService.findOneAdminWithPopulatedParentSpaceObjectRecursiveLookup(
242
          spaceObjectId
243
        )
244
    } else if (populateParent) {
245
      returnData =
246
        await this.spaceObjectService.findOneAdminWithPopulatedParentSpaceObject(
247
          spaceObjectId
248
        )
249
    } else {
250
      // no recursive parent lookup nor parent lookup, so just find the spaceObject by itself
251
      let data
252

253
      if (userId) {
254
        data = await this.spaceObjectService.findOneWithRolesCheck(
255
          userId,
256
          spaceObjectId
257
        )
258
      }
259

260
      if (isAdmin) {
261
        data = await this.spaceObjectService.findOneAdmin(spaceObjectId)
262
      }
263

264
      returnData = data.toJSON() // needs to be converted to JSON so it can be modified below
265
    }
266

267
    // check children populates
268
    if (recursiveChildrenPopulate) {
269
      const childLookup =
270
        await this.spaceObjectService.findOneAdminWithPopulatedChildSpaceObjectsRecursiveLookup(
271
          spaceObjectId
272
        )
273
      // if it worked, merge the data
274

275
      if (childLookup) {
276
        returnData['childSpaceObjects'] = childLookup.childSpaceObjects
277
      } else {
278
        returnData['childSpaceObjects'] = []
279
      }
280
    }
281

282
    return returnData
283
  }
284

285
  @SubscribeMessage(ZoneSpaceObjectWsMessage.UPDATE_BATCH)
286
  public async updateMany(
287
    @UserTokenWS('user_id') userId: UserId,
288
    @AdminTokenWS() isAdmin: boolean,
289
    @MessageBody() batchDto: UpdateBatchSpaceObjectDto
290
  ) {
291
    this.logger.log(
292
      `${JSON.stringify(
293
        {
294
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.UPDATE_BATCH,
295
          batchDto
296
        },
297
        null,
298
        2
299
      )}`,
300
      SpaceObjectGateway.name
301
    )
302

303
    if (isAdmin) {
304
      return await this.spaceObjectService.updateManyAdmin(batchDto)
305
    }
306

307
    if (userId) {
308
      return await this.spaceObjectService.updateManyWithRolesCheck(
309
        userId,
310
        batchDto
311
      )
312
    }
313
    return
314
  }
315

316
  @SubscribeMessage(ZoneSpaceObjectWsMessage.UPDATE)
317
  public updateOne(
318
    @AdminTokenWS() isAdmin: boolean,
319
    @UserTokenWS('user_id') userId: UserId,
320
    @MessageBody('id') id: string,
321
    @MessageBody('dto') updateSpaceObjectDto: UpdateSpaceObjectDto
322
  ) {
323
    this.logger.log(
324
      `${JSON.stringify(
325
        {
326
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.UPDATE,
327
          id,
328
          updateSpaceObjectDto
329
        },
330
        null,
331
        2
332
      )}`,
333
      SpaceObjectGateway.name
334
    )
335

336
    if (userId) {
337
      return this.spaceObjectService.updateOneWithRolesCheck(
338
        userId,
339
        id,
340
        updateSpaceObjectDto
341
      )
342
    }
343

344
    if (isAdmin) {
345
      return this.spaceObjectService.updateOneAdmin(id, updateSpaceObjectDto)
346
    }
347
    return
348
  }
349

350
  @SubscribeMessage(ZoneSpaceObjectWsMessage.REMOVE_BATCH)
351
  public removeMany(
352
    @UserTokenWS('user_id') userId: UserId,
353
    @AdminTokenWS() isAdmin: boolean,
354
    @MessageBody('batch') ids: string[]
355
  ) {
356
    this.logger.log(
357
      `${JSON.stringify(
358
        {
359
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.REMOVE_BATCH,
360
          'batch (ids)': ids
361
        },
362
        null,
363
        2
364
      )}`,
365
      SpaceObjectGateway.name
366
    )
367

368
    if (isAdmin) {
369
      return this.spaceObjectService.removeManyAdmin(ids)
370
    }
371

372
    if (userId) {
373
      return this.spaceObjectService.removeManyWithRolesCheck(userId, ids)
374
    }
375
    return
376
  }
377

378
  @SubscribeMessage(ZoneSpaceObjectWsMessage.REMOVE)
379
  public removeOne(
380
    @AdminTokenWS() isAdmin: boolean,
381
    @UserTokenWS('user_id') userId: UserId,
382
    @MessageBody('id') id: string
383
  ) {
384
    this.logger.log(
385
      `${JSON.stringify(
386
        {
387
          ZoneSpaceObjectWsMessage: ZoneSpaceObjectWsMessage.REMOVE,
388
          id: id
389
        },
390
        null,
391
        2
392
      )}`,
393
      SpaceObjectGateway.name
394
    )
395

396
    if (userId) {
397
      return this.spaceObjectService.removeOneWithRolesCheck(userId, id)
398
    }
399

400
    if (isAdmin) {
401
      return this.spaceObjectService.removeOneAdmin(id)
402
    }
403
    return
404
  }
405
}
406

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.