forked from noxious/server
71 lines
2.5 KiB
TypeScript
71 lines
2.5 KiB
TypeScript
import { BaseEvent } from '#application/base/baseEvent'
|
|
import { UUID } from '#application/types'
|
|
import MapManager from '#managers/mapManager'
|
|
import CharacterHairRepository from '#repositories/characterHairRepository'
|
|
import CharacterRepository from '#repositories/characterRepository'
|
|
import TeleportService from '#services/teleportService'
|
|
|
|
interface CharacterConnectPayload {
|
|
characterId: UUID
|
|
characterHairId?: UUID
|
|
}
|
|
|
|
export default class CharacterConnectEvent extends BaseEvent {
|
|
private readonly characterHairRepository = new CharacterHairRepository()
|
|
private readonly characterRepository = new CharacterRepository()
|
|
|
|
public listen(): void {
|
|
this.socket.on('character:connect', this.handleEvent.bind(this))
|
|
}
|
|
|
|
private async handleEvent(data: CharacterConnectPayload, callback: (response: any) => void): Promise<void> {
|
|
try {
|
|
if (await this.checkForActiveCharacters()) {
|
|
this.emitError('You are already connected to another character')
|
|
return
|
|
}
|
|
|
|
const character = await this.characterRepository.getByUserAndId(this.socket.userId!, data.characterId)
|
|
|
|
if (!character) {
|
|
this.emitError('Character not found or does not belong to this user')
|
|
return
|
|
}
|
|
|
|
// Populate character with characterType and characterHair
|
|
await this.characterRepository.getEntityManager().populate(character, ['characterType', 'characterHair'])
|
|
|
|
// Set character id
|
|
this.socket.characterId = character.id
|
|
|
|
// Set character hair
|
|
if (data.characterHairId !== undefined && data.characterHairId !== null) {
|
|
const characterHair = await this.characterHairRepository.getById(data.characterHairId)
|
|
await character.setCharacterHair(characterHair).save()
|
|
}
|
|
|
|
// Emit character connect event
|
|
callback({ character })
|
|
|
|
// wait 300 ms, @TODO: Find a better way to do this, race condition
|
|
await new Promise((resolve) => setTimeout(resolve, 500))
|
|
|
|
await TeleportService.teleportCharacter(character.id, {
|
|
targetMapId: character.map.id,
|
|
targetX: character.positionX,
|
|
targetY: character.positionY,
|
|
rotation: character.rotation,
|
|
isInitialJoin: true,
|
|
character
|
|
})
|
|
} catch (error) {
|
|
this.handleError('Failed to connect character', error)
|
|
}
|
|
}
|
|
|
|
private async checkForActiveCharacters(): Promise<boolean> {
|
|
const characters = await this.characterRepository.getByUserId(this.socket.userId!)
|
|
return characters?.some((char) => MapManager.getCharacterById(char.id)) ?? false
|
|
}
|
|
}
|