server/src/events/character/connect.ts
2025-01-01 04:48:30 +01:00

81 lines
2.6 KiB
TypeScript

import { BaseEvent } from '#application/base/baseEvent'
import Database from '#application/database'
import ZoneManager from '#managers/zoneManager'
import CharacterHairRepository from '#repositories/characterHairRepository'
import CharacterRepository from '#repositories/characterRepository'
import TeleportService from '#services/teleportService'
interface CharacterConnectPayload {
characterId: number
characterHairId?: number
}
export default class CharacterConnectEvent extends BaseEvent {
public listen(): void {
this.socket.on('character:connect', this.handleEvent.bind(this))
}
/**
* Handle character connect event
* @TODO:
* 1. Check if character is already connected
* 2. Update character hair if provided
* 3. Emit character connect event
* 4. Let other clients know of new character
* @param data
* @param callback
* @private
*/
private async handleEvent(data: CharacterConnectPayload, callback: (response: any) => void): Promise<void> {
if (!this.socket.userId) {
this.emitError('User not authenticated')
return
}
try {
if (await this.checkForActiveCharacters()) {
this.emitError('You are already connected to another character')
return
}
const character = await CharacterRepository.getByUserAndId(this.socket.userId, data.characterId)
if (!character) {
this.emitError('Character not found or does not belong to this user')
return
}
// Set character id
this.socket.characterId = character.id
// Set character hair
if (data.characterHairId !== undefined && data.characterHairId !== null) {
const characterHair = await CharacterHairRepository.getById(data.characterHairId)
await character.setCharacterHair(characterHair).update()
}
// Emit character connect event
callback({ character })
// wait 300 ms, @TODO: Find a better way to do this
await new Promise((resolve) => setTimeout(resolve, 100))
await TeleportService.teleportCharacter(character.id, {
targetZoneId: character.zone.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 CharacterRepository.getByUserId(this.socket.userId!)
return characters?.some((char) => ZoneManager.getCharacterById(char.id)) ?? false
}
}