UNPKG

adaptorex

Version:

Connect all your live interactive storytelling devices and software

111 lines (95 loc) 3.12 kB
/** @typedef {import('../game.js').Game} Game */ /** @typedef {import('../types').SessionInterface} Session */ class Action { constructor(data, session, game) { for(let prop in data) { this[prop] = data[prop] } /** @type {Session} */ this.session = session /** @type {Game} */ this.game = game this.log = this.session.log } /** * */ async reaction(data) { this.session.log.warn("Try to respond but no response callback defined.") } /** * start timer for `while_idle` and `finally` events that happen if nothing happens. * * Only start timer if action status is "active" */ whileIdle() { if (this.session.action.status == "active") { if (this.hasOwnProperty("while_idle") && this.while_idle.length) { this.setDelay(this.while_idle[0].delay) } else if (this.hasOwnProperty("finally")) { this.setDelay(this.finally.delay) } } } /** * Idle time Event dispatched after delay passed * * If there are more delayed messages the next timer is started. Otherwise (if any) "finally" next state. */ async time() { if (!this.while_idle && this.finally) { return this.session.next(this.finally.next) } if (!this.while_idle.length && this.finally) { return this.session.next(this.finally.next) } let next_message = this.while_idle.shift() try { await this.reaction(next_message.message) } catch (error) { if (error instanceof adaptor.AdaptorError) { this.session.log.error(error.name + " when sending delayed message") this.session.log.error(error.message) } } if (this.while_idle.length) { this.setDelay(this.while_idle[0].delay) } else if (this.finally) { if (this.finally.delay) { this.setDelay(this.finally.delay) } else { return this.session.next(this.finally.next) } } else { this.session.log(`No more delayed messages.`) } } setDelay(delay) { if (!this.delayed_messages_canceled) { this.session.log("Next idle response in " + delay + " seconds") this.timer = setTimeout(this.time.bind(this), delay * 1000) } } /** * clear current delayed message timeout and prevent creating new delayed message timeouts */ cancelDelayedMessages() { if (!this.delayed_messages_canceled) { this.session.log("delayed message timeout canceled") this.delayed_messages_canceled = true clearTimeout(this.timer) } } mute() { if (this.hasOwnProperty("while_idle")) { this.cancelDelayedMessages() } this.session.log("action muted") } unmute() { this.session.log(`unmute action`) } } module.exports = { Action: Action }