snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
239
apps/meteor/server/bridges/irc/irc-bridge/index.js
Normal file
239
apps/meteor/server/bridges/irc/irc-bridge/index.js
Normal file
@@ -0,0 +1,239 @@
|
||||
import { Logger } from '@rocket.chat/logger';
|
||||
import { Settings } from '@rocket.chat/models';
|
||||
import moment from 'moment';
|
||||
import Queue from 'queue-fifo';
|
||||
|
||||
import * as localCommandHandlers from './localHandlers';
|
||||
import * as peerCommandHandlers from './peerHandlers';
|
||||
import { withThrottling } from '../../../../lib/utils/highOrderFunctions';
|
||||
import { callbacks } from '../../../lib/callbacks';
|
||||
import { afterLeaveRoomCallback } from '../../../lib/callbacks/afterLeaveRoomCallback';
|
||||
import { afterLogoutCleanUpCallback } from '../../../lib/callbacks/afterLogoutCleanUpCallback';
|
||||
import { notifyOnSettingChangedById } from '../../../lib/notifyListener';
|
||||
import { updateAuditedBySystem } from '../../../settings/lib/auditedSettingUpdates';
|
||||
import * as servers from '../servers';
|
||||
|
||||
const logger = new Logger('IRC Bridge');
|
||||
const queueLogger = logger.section('Queue');
|
||||
|
||||
let removed = false;
|
||||
const updateLastPing = withThrottling({ wait: 10_000 })(() => {
|
||||
if (removed) {
|
||||
return;
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
const updatedValue = await updateAuditedBySystem({
|
||||
reason: 'updateLastPing',
|
||||
})(Settings.updateValueById, 'IRC_Bridge_Last_Ping', new Date(), { upsert: true });
|
||||
if (updatedValue.modifiedCount || updatedValue.upsertedCount) {
|
||||
void notifyOnSettingChangedById('IRC_Bridge_Last_Ping');
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
class Bridge {
|
||||
constructor(config) {
|
||||
// General
|
||||
this.config = config;
|
||||
|
||||
// Workaround for Rocket.Chat callbacks being called multiple times
|
||||
this.loggedInUsers = [];
|
||||
|
||||
// Server
|
||||
const Server = servers[this.config.server.protocol];
|
||||
|
||||
this.server = new Server(this.config);
|
||||
|
||||
this.setupPeerHandlers();
|
||||
this.setupLocalHandlers();
|
||||
|
||||
// Command queue
|
||||
this.queue = new Queue();
|
||||
this.queueTimeout = 5;
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.initTime = new Date();
|
||||
removed = false;
|
||||
this.loggedInUsers = [];
|
||||
|
||||
const lastPing = await Settings.findOneById('IRC_Bridge_Last_Ping');
|
||||
if (lastPing) {
|
||||
if (Math.abs(moment(lastPing.value).diff()) < 1000 * 30) {
|
||||
this.log('Not trying to connect.');
|
||||
this.remove();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.log('Connecting.');
|
||||
updateLastPing();
|
||||
this.server.register();
|
||||
|
||||
this.server.on('registered', () => {
|
||||
this.logQueue('Starting...');
|
||||
|
||||
this.runQueue();
|
||||
});
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.server.disconnect();
|
||||
}
|
||||
|
||||
remove() {
|
||||
this.log('Removing current connection.');
|
||||
removed = true;
|
||||
this.server = null;
|
||||
this.removeLocalHandlers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Log helper
|
||||
*/
|
||||
log(message) {
|
||||
// TODO logger: debug?
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
logQueue(message) {
|
||||
// TODO logger: debug?
|
||||
queueLogger.info(message);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Queue
|
||||
*
|
||||
*
|
||||
*/
|
||||
onMessageReceived(from, command, ...parameters) {
|
||||
this.queue.enqueue({ from, command, parameters });
|
||||
}
|
||||
|
||||
async runQueue() {
|
||||
if (!this.server) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastResetTime = Settings.findOneById('IRC_Bridge_Reset_Time');
|
||||
if (lastResetTime && lastResetTime.value > this.initTime) {
|
||||
this.stop();
|
||||
this.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
updateLastPing();
|
||||
|
||||
// If it is empty, skip and keep the queue going
|
||||
if (this.queue.isEmpty()) {
|
||||
return setTimeout(this.runQueue.bind(this), this.queueTimeout);
|
||||
}
|
||||
|
||||
// Get the command
|
||||
const item = this.queue.dequeue();
|
||||
|
||||
this.logQueue({ msg: 'Processing command from source', command: item.command, from: item.from });
|
||||
|
||||
// Handle the command accordingly
|
||||
try {
|
||||
// Handle the command accordingly
|
||||
switch (item.from) {
|
||||
case 'local':
|
||||
if (!localCommandHandlers[item.command]) {
|
||||
throw new Error(`Could not find handler for local:${item.command}`);
|
||||
}
|
||||
|
||||
await localCommandHandlers[item.command].apply(this, item.parameters);
|
||||
break;
|
||||
case 'peer':
|
||||
if (!peerCommandHandlers[item.command]) {
|
||||
throw new Error(`Could not find handler for peer:${item.command}`);
|
||||
}
|
||||
|
||||
await peerCommandHandlers[item.command].apply(this, item.parameters);
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
this.logQueue(e);
|
||||
}
|
||||
|
||||
// Keep the queue going
|
||||
setTimeout(this.runQueue.bind(this), this.queueTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Peer
|
||||
*
|
||||
*
|
||||
*/
|
||||
setupPeerHandlers() {
|
||||
this.server.on('peerCommand', (cmd) => {
|
||||
this.onMessageReceived('peer', cmd.identifier, cmd.args);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* Local
|
||||
*
|
||||
*
|
||||
*/
|
||||
setupLocalHandlers() {
|
||||
// Auth
|
||||
callbacks.add('afterValidateLogin', this.onMessageReceived.bind(this, 'local', 'onLogin'), callbacks.priority.LOW, 'irc-on-login');
|
||||
callbacks.add(
|
||||
'afterCreateUser',
|
||||
this.onMessageReceived.bind(this, 'local', 'onCreateUser'),
|
||||
callbacks.priority.LOW,
|
||||
'irc-on-create-user',
|
||||
);
|
||||
// Joining rooms or channels
|
||||
callbacks.add(
|
||||
'afterCreateChannel',
|
||||
this.onMessageReceived.bind(this, 'local', 'onCreateRoom'),
|
||||
callbacks.priority.LOW,
|
||||
'irc-on-create-channel',
|
||||
);
|
||||
callbacks.add(
|
||||
'afterCreateRoom',
|
||||
this.onMessageReceived.bind(this, 'local', 'onCreateRoom'),
|
||||
callbacks.priority.LOW,
|
||||
'irc-on-create-room',
|
||||
);
|
||||
callbacks.add('afterJoinRoom', this.onMessageReceived.bind(this, 'local', 'onJoinRoom'), callbacks.priority.LOW, 'irc-on-join-room');
|
||||
// Leaving rooms or channels
|
||||
afterLeaveRoomCallback.add(this.onMessageReceived.bind(this, 'local', 'onLeaveRoom'), callbacks.priority.LOW, 'irc-on-leave-room');
|
||||
// Chatting
|
||||
callbacks.add(
|
||||
'afterSaveMessage',
|
||||
(message, { room }) => this.onMessageReceived('local', 'onSaveMessage', message, room),
|
||||
callbacks.priority.LOW,
|
||||
'irc-on-save-message',
|
||||
);
|
||||
// Leaving
|
||||
afterLogoutCleanUpCallback.add(this.onMessageReceived.bind(this, 'local', 'onLogout'), callbacks.priority.LOW, 'irc-on-logout');
|
||||
}
|
||||
|
||||
removeLocalHandlers() {
|
||||
callbacks.remove('afterValidateLogin', 'irc-on-login');
|
||||
callbacks.remove('afterCreateUser', 'irc-on-create-user');
|
||||
callbacks.remove('afterCreateChannel', 'irc-on-create-channel');
|
||||
callbacks.remove('afterCreateRoom', 'irc-on-create-room');
|
||||
callbacks.remove('afterJoinRoom', 'irc-on-join-room');
|
||||
afterLeaveRoomCallback.remove('irc-on-leave-room');
|
||||
callbacks.remove('afterSaveMessage', 'irc-on-save-message');
|
||||
afterLogoutCleanUpCallback.remove('irc-on-logout');
|
||||
}
|
||||
|
||||
sendCommand(command, parameters) {
|
||||
this.server.emit('onReceiveFromLocal', command, parameters);
|
||||
}
|
||||
}
|
||||
|
||||
export default Bridge;
|
||||
@@ -0,0 +1,9 @@
|
||||
import onCreateRoom from './onCreateRoom';
|
||||
import onCreateUser from './onCreateUser';
|
||||
import onJoinRoom from './onJoinRoom';
|
||||
import onLeaveRoom from './onLeaveRoom';
|
||||
import onLogin from './onLogin';
|
||||
import onLogout from './onLogout';
|
||||
import onSaveMessage from './onSaveMessage';
|
||||
|
||||
export { onCreateRoom, onJoinRoom, onLeaveRoom, onLogin, onLogout, onSaveMessage, onCreateUser };
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Users } from '@rocket.chat/models';
|
||||
|
||||
export default async function handleOnCreateRoom(user, room) {
|
||||
const users = await Users.findByRoomId(room._id);
|
||||
|
||||
users.forEach((user) => {
|
||||
if (user.profile?.irc?.fromIRC) {
|
||||
this.sendCommand('joinChannel', { room, user });
|
||||
} else {
|
||||
this.sendCommand('joinedChannel', { room, user });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Rooms, Users } from '@rocket.chat/models';
|
||||
|
||||
export default async function handleOnCreateUser(newUser) {
|
||||
if (!newUser) {
|
||||
return this.log('Invalid handleOnCreateUser call');
|
||||
}
|
||||
if (!newUser.username) {
|
||||
return this.log('Invalid handleOnCreateUser call (Missing username)');
|
||||
}
|
||||
if (this.loggedInUsers.indexOf(newUser._id) !== -1) {
|
||||
return this.log('Duplicate handleOnCreateUser call');
|
||||
}
|
||||
|
||||
this.loggedInUsers.push(newUser._id);
|
||||
|
||||
await Users.updateOne(
|
||||
{ _id: newUser._id },
|
||||
{
|
||||
$set: {
|
||||
'profile.irc.fromIRC': false,
|
||||
'profile.irc.username': `${newUser.username}-rkt`,
|
||||
'profile.irc.nick': `${newUser.username}-rkt`,
|
||||
'profile.irc.hostname': 'rocket.chat',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const user = await Users.findOne({
|
||||
_id: newUser._id,
|
||||
});
|
||||
|
||||
this.sendCommand('registerUser', user);
|
||||
|
||||
const rooms = await Rooms.findBySubscriptionUserId(user._id).toArray();
|
||||
|
||||
rooms.forEach((room) => this.sendCommand('joinedChannel', { room, user }));
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default async function handleOnJoinRoom(user, room) {
|
||||
this.sendCommand('joinedChannel', { room, user });
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export default async function handleOnLeaveRoom(user, room) {
|
||||
this.sendCommand('leftChannel', { room, user });
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { Rooms, Users } from '@rocket.chat/models';
|
||||
|
||||
export default async function handleOnLogin(login) {
|
||||
if (login.user === null) {
|
||||
return this.log('Invalid handleOnLogin call');
|
||||
}
|
||||
if (!login.user.username) {
|
||||
return this.log('Invalid handleOnLogin call (Missing username)');
|
||||
}
|
||||
if (this.loggedInUsers.indexOf(login.user._id) !== -1) {
|
||||
return this.log('Duplicate handleOnLogin call');
|
||||
}
|
||||
|
||||
this.loggedInUsers.push(login.user._id);
|
||||
|
||||
await Users.updateOne(
|
||||
{ _id: login.user._id },
|
||||
{
|
||||
$set: {
|
||||
'profile.irc.fromIRC': false,
|
||||
'profile.irc.username': `${login.user.username}-rkt`,
|
||||
'profile.irc.nick': `${login.user.username}-rkt`,
|
||||
'profile.irc.hostname': 'rocket.chat',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const user = await Users.findOne({
|
||||
_id: login.user._id,
|
||||
});
|
||||
|
||||
this.sendCommand('registerUser', user);
|
||||
const rooms = await Rooms.findBySubscriptionUserId(user._id).toArray();
|
||||
|
||||
rooms.forEach((room) => {
|
||||
if (room.t === 'd') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.sendCommand('joinedChannel', { room, user });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import _ from 'underscore';
|
||||
|
||||
export default async function handleOnLogout(user) {
|
||||
this.loggedInUsers = _.without(this.loggedInUsers, user._id);
|
||||
|
||||
this.sendCommand('disconnected', { user });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Subscriptions, Users } from '@rocket.chat/models';
|
||||
|
||||
import { SystemLogger } from '../../../../lib/logger/system';
|
||||
|
||||
export default async function handleOnSaveMessage(message, to) {
|
||||
let toIdentification = '';
|
||||
// Direct message
|
||||
if (to.t === 'd') {
|
||||
const subscriptions = Subscriptions.findByRoomId(to._id).toArray();
|
||||
for await (const subscription of subscriptions) {
|
||||
if (subscription.u._id !== message.u._id) {
|
||||
const userData = await Users.findOne({ username: subscription.u.username });
|
||||
if (userData) {
|
||||
if (userData.profile && userData.profile.irc && userData.profile.irc.nick) {
|
||||
toIdentification = userData.profile.irc.nick;
|
||||
} else {
|
||||
toIdentification = userData.username;
|
||||
}
|
||||
} else {
|
||||
toIdentification = subscription.u.username;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!toIdentification) {
|
||||
SystemLogger.error('[irc][server] Target user not found');
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
toIdentification = `#${to.name}`;
|
||||
}
|
||||
|
||||
const user = await Users.findOne({ _id: message.u._id });
|
||||
|
||||
this.sendCommand('sentMessage', { to: toIdentification, user, message: message.msg });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Users } from '@rocket.chat/models';
|
||||
|
||||
import { notifyOnUserChange } from '../../../../lib/notifyListener';
|
||||
|
||||
export default async function handleQUIT(args) {
|
||||
const user = await Users.findOne({
|
||||
'profile.irc.nick': args.nick,
|
||||
});
|
||||
|
||||
await Users.updateOne(
|
||||
{ _id: user._id },
|
||||
{
|
||||
$set: {
|
||||
status: 'offline',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
void notifyOnUserChange({ id: user._id, clientAction: 'updated', diff: { status: 'offline' } });
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import disconnected from './disconnected';
|
||||
import joinedChannel from './joinedChannel';
|
||||
import leftChannel from './leftChannel';
|
||||
import nickChanged from './nickChanged';
|
||||
import sentMessage from './sentMessage';
|
||||
import userRegistered from './userRegistered';
|
||||
|
||||
export { disconnected, joinedChannel, leftChannel, nickChanged, sentMessage, userRegistered };
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Users, Rooms } from '@rocket.chat/models';
|
||||
|
||||
import { addUserToRoom } from '../../../../lib/rooms/addUserToRoom';
|
||||
import { createRoom } from '../../../../lib/rooms/createRoom';
|
||||
|
||||
// TODO doesn't seem to be used anywhere, remove
|
||||
export default async function handleJoinedChannel(args) {
|
||||
const user = await Users.findOne({
|
||||
'profile.irc.nick': args.nick,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`Could not find a user with nick ${args.nick}`);
|
||||
}
|
||||
|
||||
let room = await Rooms.findOneByName(args.roomName);
|
||||
|
||||
if (!room) {
|
||||
const createdRoom = await createRoom('c', args.roomName, user, []);
|
||||
room = await Rooms.findOne({ _id: createdRoom.rid });
|
||||
|
||||
this.log(`${user.username} created room ${args.roomName}`);
|
||||
} else {
|
||||
await addUserToRoom(room._id, user);
|
||||
|
||||
this.log(`${user.username} joined room ${room.name}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Users, Rooms } from '@rocket.chat/models';
|
||||
|
||||
import { removeUserFromRoom } from '../../../../lib/rooms/removeUserFromRoom';
|
||||
|
||||
export default async function handleLeftChannel(args) {
|
||||
const user = await Users.findOne({
|
||||
'profile.irc.nick': args.nick,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`Could not find a user with nick ${args.nick}`);
|
||||
}
|
||||
|
||||
const room = await Rooms.findOneByName(args.roomName);
|
||||
|
||||
if (!room) {
|
||||
throw new Error(`Could not find a room with name ${args.roomName}`);
|
||||
}
|
||||
|
||||
this.log(`${user.username} left room ${room.name}`);
|
||||
await removeUserFromRoom(room._id, user);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Users } from '@rocket.chat/models';
|
||||
|
||||
import { notifyOnUserChange } from '../../../../lib/notifyListener';
|
||||
|
||||
export default async function handleNickChanged(args) {
|
||||
const user = await Users.findOne({
|
||||
'profile.irc.nick': args.nick,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`Could not find an user with nick ${args.nick}`);
|
||||
}
|
||||
|
||||
this.log(`${user.username} changed nick: ${args.nick} -> ${args.newNick}`);
|
||||
|
||||
// Update on the database
|
||||
await Users.updateOne(
|
||||
{ _id: user._id },
|
||||
{
|
||||
$set: {
|
||||
'name': args.newNick,
|
||||
'profile.irc.nick': args.newNick,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
void notifyOnUserChange({ clientAction: 'updated', id: user._id, diff: { name: args.newNick } });
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Users, Rooms } from '@rocket.chat/models';
|
||||
|
||||
import { sendMessage } from '../../../../lib/messages/sendMessage';
|
||||
import { createDirectRoom } from '../../../../lib/rooms/createDirectRoom';
|
||||
|
||||
/*
|
||||
*
|
||||
* Get direct chat room helper
|
||||
*
|
||||
*
|
||||
*/
|
||||
const getDirectRoom = async (source, target) => {
|
||||
const uids = [source._id, target._id];
|
||||
const { _id, ...extraData } = await createDirectRoom([source, target]);
|
||||
|
||||
const room = await Rooms.findOneDirectRoomContainingAllUserIDs(uids);
|
||||
if (room) {
|
||||
return {
|
||||
t: 'd',
|
||||
...room,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
_id,
|
||||
t: 'd',
|
||||
...extraData,
|
||||
};
|
||||
};
|
||||
|
||||
export default async function handleSentMessage(args) {
|
||||
const user = await Users.findOne({
|
||||
'profile.irc.nick': args.nick,
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`Could not find a user with nick ${args.nick}`);
|
||||
}
|
||||
|
||||
let room;
|
||||
|
||||
if (args.roomName) {
|
||||
room = await Rooms.findOneByName(args.roomName);
|
||||
} else {
|
||||
const recipientUser = await Users.findOne({
|
||||
'profile.irc.nick': args.recipientNick,
|
||||
});
|
||||
|
||||
room = await getDirectRoom(user, recipientUser);
|
||||
}
|
||||
|
||||
const message = {
|
||||
msg: args.message,
|
||||
ts: new Date(),
|
||||
};
|
||||
|
||||
await sendMessage(user, message, room);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Users } from '@rocket.chat/models';
|
||||
|
||||
import { notifyOnUserChange } from '../../../../lib/notifyListener';
|
||||
|
||||
export default async function handleUserRegistered(args) {
|
||||
// Check if there is an user with the given username
|
||||
let user = await Users.findOne({
|
||||
'profile.irc.username': args.username,
|
||||
});
|
||||
|
||||
// If there is no user, create one...
|
||||
if (!user) {
|
||||
this.log(`Registering ${args.username} with nick: ${args.nick}`);
|
||||
|
||||
const userToInsert = {
|
||||
name: args.nick,
|
||||
username: `${args.username}-irc`,
|
||||
status: 'online',
|
||||
utcOffset: 0,
|
||||
active: true,
|
||||
type: 'user',
|
||||
profile: {
|
||||
irc: {
|
||||
fromIRC: true,
|
||||
nick: args.nick,
|
||||
username: args.username,
|
||||
hostname: args.hostname,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
user = await Users.create(userToInsert);
|
||||
|
||||
void notifyOnUserChange({ id: user._id, clientAction: 'inserted', data: user });
|
||||
} else {
|
||||
// ...otherwise, log the user in and update the information
|
||||
this.log(`Logging in ${args.username} with nick: ${args.nick}`);
|
||||
|
||||
await Users.updateOne(
|
||||
{ _id: user._id },
|
||||
{
|
||||
$set: {
|
||||
'status': 'online',
|
||||
'profile.irc.nick': args.nick,
|
||||
'profile.irc.username': args.username,
|
||||
'profile.irc.hostname': args.hostname,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
void notifyOnUserChange({ id: user._id, clientAction: 'updated', diff: { status: 'online' } });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user