handle_request = (args) => {
let {action, client_id, channel, name=channel, recipient, body, sender} = args
const err = msg => (console.log(msg), connections[client_id]({error: msg}))
console.log('Server: request:', args)
const K = Object.keys
const V = Object.values
const s = K(sessions).find(name1 => name1 == name)
|| (!name && V(sessions).find(s => s[client_id])) || undefined;
const R = args => {
console.log('responding', args)
connections[client_id]({action, response: args, client_id})
console.log('responded')
}
const session = sessions[s] || s
const ops = {
list: () =>
s ? R(K(session))
: R({sessions: K(sessions)
.map(s => ({name: s.name}))}),
join: () => {
if (!name) return err(`can't join with session name ${name}`)
if (!session) return sessions[name] = {[client_id] : true}
session[client_id] = true
update_clients(session)
},
leave: () => {
const session = sessions[s]
if (!s || !session || !session[client_id]) return err(`You're not in that session.`)
delete session[client_id] && update_clients(session)
if (Object.keys(session).length == 0) delete sessions[s]
return true
},
message: () =>
!s ? err("You need to be in a session to send a message.")
: !(session[client_id] && session[recipient]) ? err("Couldn't find that recipient in your session.")
: connections[recipient]({action, sender: client_id, name, body, recipient})
}
if (!Object.keys(ops).includes(action)) {console.log('Invalid action'); return}
ops[action]()
}