1
0
forked from noxious/server

#184: Allow GMs to set time

This commit is contained in:
Dennis Postma 2024-11-05 23:07:23 +01:00
parent ae0241fecb
commit 26dbaa45a7
2 changed files with 88 additions and 4 deletions

View File

@ -18,10 +18,28 @@ class DateManager {
appLogger.info('Date manager loaded')
}
public stop(): void {
if (this.intervalId) {
clearInterval(this.intervalId)
this.intervalId = null
// When a GM sets the time, update the current date and update the world file
public async setTime(time: string): Promise<void> {
try {
let newDate: Date;
// Check if it's just a time (HH:mm or HH:mm:ss format)
if (/^\d{1,2}:\d{2}(:\d{2})?$/.test(time)) {
const [hours, minutes] = time.split(':').map(Number);
newDate = new Date(this.currentDate); // Clone current date
newDate.setHours(hours, minutes);
} else {
// Treat as full datetime string
newDate = new Date(time);
if (isNaN(newDate.getTime())) return;
}
this.currentDate = newDate;
this.emitDate();
await this.saveDate();
} catch (error) {
appLogger.error(`Failed to set time: ${error instanceof Error ? error.message : String(error)}`);
throw error;
}
}

View File

@ -0,0 +1,66 @@
import { Server } from 'socket.io'
import { TSocket } from '../../../utilities/types'
import { getArgs, isCommand } from '../../../utilities/chat'
import CharacterRepository from '../../../repositories/characterRepository'
import { gameLogger } from '../../../utilities/logger'
import DateManager from '../../../managers/dateManager'
type TypePayload = {
message: string
}
export default class SetTimeCommand {
constructor(
private readonly io: Server,
private readonly socket: TSocket
) {}
public listen(): void {
this.socket.on('chat:send_message', this.handleAlertCommand.bind(this))
}
private async handleAlertCommand(data: TypePayload, callback: (response: boolean) => void): Promise<void> {
try {
if (!isCommand(data.message, 'time')) {
return
}
// Check if character exists
const character = await CharacterRepository.getByUserAndId(this.socket.user?.id as number, this.socket.characterId as number)
if (!character) {
gameLogger.error('chat:alert_command error', 'Character not found')
callback(false)
return
}
// Check if the user is the GM
if (character.role !== 'gm') {
gameLogger.info(`User ${character.id} tried to set time but is not a game master.`)
callback(false)
return
}
// Get arguments
const args = getArgs('time', data.message)
if (!args) {
callback(false)
return
}
const time = args[0] // 24h time, e.g. 17:34
if (!time) {
callback(false)
return
}
await DateManager.setTime(time)
callback(true)
} catch (error: any) {
gameLogger.error('command error', error.message)
callback(false)
}
}
}