seepur/app/Controllers/Ws/UserChannelController.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-04-12 14:25:42 +00:00
'use strict'
const UserChildUtils = use('App/Utils/UserChildUtils');
const connectedUsers = {
};
class UserChannelController {
constructor({socket, request, auth}) {
console.log(`User #${auth.user.id} connected`);
this.socket = socket;
this.request = request;
this.user = auth.user;
connectedUsers[this.user.id] = this;
this.notifyOnConnection(true).catch(console.error);
// socket.on('close', this.onClose.bind(this))
}
onClose() {
this.notifyOnConnection(false)
.then(_ => {
delete connectedUsers[this.user.id];
})
.catch(console.error);
}
emit(event, data) {
2020-04-13 01:52:08 +00:00
console.log(`sending ${event} to user #${this.user.id}`);
2020-04-12 14:25:42 +00:00
this.socket.emit(event, data);
}
static getUserChannel(userId) {
2020-04-13 01:52:08 +00:00
console.log(`user ${userId} has socket? ${!!connectedUsers[userId]}`)
2020-04-12 14:25:42 +00:00
return connectedUsers[userId];
}
static isUserOnline(userId) {
return !!UserChannelController.getUserChannel(userId);
}
async notifyOnConnection(online) {
this.user.last_logged_in = new Date();
try {
await this.user.save();
} catch (e) {
console.error(e);
}
const userConnections =
await UserChildUtils.getUserConnections(this.user.id);
const notifiedIds = [];
for (const child of userConnections.children) {
for (const user of child.connections) {
const channel = UserChannelController.getUserChannel(user.id);
if (channel && notifiedIds.indexOf(user.id) < 0 &&
user.id != this.user.id) {
/// connection:online
channel.emit(
`connection:${online ? 'online' : 'offline'}`,
this.user.toJSON());
notifiedIds.push(user.id);
}
}
}
for (const child of userConnections.connections) {
for (const user of child.connections) {
const channel = UserChannelController.getUserChannel(user.id);
if (channel && notifiedIds.indexOf(user.id) < 0 &&
user.id != this.user.id) {
channel.emit(
`connection:${online ? 'online' : 'offline'}`,
this.user.toJSON());
notifiedIds.push(user.id);
}
}
}
return true;
}
}
module.exports = UserChannelController